【发布时间】:2014-10-29 23:39:42
【问题描述】:
我正在编写一个拼写检查程序,它会询问用户一个单词并将其与我创建的数组中的单词列表进行比较。
在用户输入quit 之前,该程序必须永远不会结束。
所以我的问题是,当用户输入 quit 而不是输入另一个单词时,我会输入什么 while(>> here <<) 来结束程序。单词quit 不在数组中。
这是我目前的 while 循环代码(还没有完成,但是当我测试它并且循环不会在退出时结束,所以这是我需要首先完成的)。
String quit = "quit";
//this is only declared as "quit" to get the loop to run for testing
while(quit.equals("quit")) {
System.out.println("Please every a word or QUIT to exit");
String guess = input.nextLine();
for(int i = 0; i < words.length; i++) {
if(guess.equals(words[i])) {
System.out.println("That word is spelled correctly.");
}
else {
System.out.println("That word is not spelled correctly.");
System.out.println("Would you like to add it to the dictionary? (Y/N)");
}
}
}
如果您建议另一种不是 while 循环的方法,尽管我很欣赏它,它必须是一个 while 循环用于学校目的。
【问题讨论】:
-
您说输入
QUIT,但equals()不会忽略大小写。此外,如果您希望循环运行直到有人键入退出,您可能希望在条件中使用!... -
使用
do-while循环并检查value是否不等于quite...do {...} while (!guess.equalsIgnoreCase("quit"));
标签: java loops if-statement for-loop while-loop