gpt4 book ai didi

使用队列的 Java Pig 拉丁语句子翻译器

转载 作者:行者123 更新时间:2023-11-30 04:17:07 25 4
gpt4 key购买 nike

我对 Java 很陌生,正在尝试创建一个程序将句子翻译成 Pig Latin,将单词的第一个字母移到末尾,如果第一个字母是元音,则在末尾附加“y”,并且否则以“ay”结尾。我需要为此使用队列。目前我的程序刚刚终止,我想知道是否有人能够发现我哪里出了问题或者下一步该去哪里。谢谢!

导入MyQueue.QueueList;导入java.util.Scanner;

公共(public)课PigLatin {

public static void main (String[] args)
{


Scanner scan = new Scanner (System.in);

QueueList word = new QueueList();

String message;
int index = 0;
char firstch;
System.out.print ("Enter an English sentence: ");
message = scan.nextLine();
System.out.println ("The equivalent Pig Latin sentence is: ");

firstch = Character.toLowerCase(message.charAt(0));


if (firstch != 'a' && firstch != 'e' && firstch != 'i' && firstch != 'o' && firstch != 'u'
&& firstch != ' ')
{
for (index = 1; index < message.length(); index++)

{
word.enqueue(new Character(message.charAt(index)));
}

word.enqueue(new Character (firstch));
word.enqueue(new Character ('a'));
word.enqueue(new Character ('y'));
word.enqueue(new Character(' '));

}

else if (firstch == 'a' || firstch == 'e' || firstch == 'i' || firstch == 'o' || firstch == 'u')
{
while (message.charAt(index) != ' ')
{
for (index = 1; index < message.length(); index++)
{
word.enqueue(new Character(message.charAt(index)));
}
}
word.enqueue((firstch));
word.enqueue( ('y'));
word.enqueue((' '));
}
else if (message.charAt(index) == ' ')
{
index++;
firstch = message.charAt(index);
}



while (!word.empty())
System.out.print(word.dequeue());

}

}

这是 MyQueue 包中的 QueueList 类:

// QueueList.java
//
// Class QueueList definition with composed List object.

package MyQueue;

public class QueueList {

private List a_queue;

public QueueList() {
a_queue = new List( "queue" );
}

public Object peek() throws EmptyListException {
if (a_queue.isEmpty())
return null;
else
return a_queue.getFirstObject();
}

public void print() {
a_queue.print();
}

public void enqueue(Object object) {
a_queue.insertAtBack(object);
}

public Object dequeue() throws EmptyListException {
return a_queue.removeFromFront();
}

public boolean empty() {
return a_queue.isEmpty();
}

}

最佳答案

在进入第二个 while 循环之前,您没有将索引重置为 0。由于第一个循环结束后 index == message.length(),第二个循环立即终止。

编辑:回复:您的最新更新。

在第二个循环中,您仅将第一个 message.length() 字符从字队列中出列。如果您在末尾添加了 -ay,您将看不到它。相反,循环队列的长度,而不是输入消息的长度:

while (!word.empty())
System.out.print(word.dequeue());

我可以发现您的逻辑存在许多其他问题(您没有删除第一个字母,也没有处理句子中的单个单词),但是上述更改应该足以让您打印队列中的内容并将其发送给您正在调试中。

关于使用队列的 Java Pig 拉丁语句子翻译器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18093785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com