我对Java非常陌生,正在尝试创建一个程序来将句子翻译成Pig拉丁语,将单词的第一个字母移到末尾,如果第一个字母是元音,则在末尾附加"y“,否则在末尾附加"ay”。为此,我需要使用队列。目前,我的程序刚刚结束,我想知道是否有人能够发现我的错误所在,或者下一步该去哪里。谢谢!
导入MyQueue.QueueList;导入java.util.Scanner;
公共类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();
}
}
发布于 2013-08-07 10:56:16
在进入第二个while循环之前,您没有将索引重置为0。由于第一个循环后的index == message.length()
结束,因此第二个循环立即终止。
编辑: Re:您的最新更新。
在第二个循环中,您只将单词队列中的第一个message.length()字符出队。如果你在最后添加了-ay,你就看不到它了。相反,循环队列的长度,而不是输入消息的长度:
while (!word.empty())
System.out.print(word.dequeue());
我可以在您的逻辑中发现许多其他问题(您没有删除第一个字母,也没有处理句子中的单个单词),但上面的更改应该足以让您打印队列中的内容,并让您继续进行调试。
https://stackoverflow.com/questions/18093785
复制相似问题