Java - 是/否循环

时间:2016-03-27 13:01:45

标签: java

System.out.println("\nWould you like to order some coffee, " + customerName + "? (y/n)");

char response = keyboard.next().charAt(0);
while (response != 'y' && response != 'n') {
  System.out.println("\nInvalid response. Try again.");
  response = keyboard.next().charAt(0);
} if (response == 'n') {
  System.out.println("\nCome back next time, " + customerName + ".");
} else if (response == 'y') {
  System.out.println("\nGreat! Let's get started.");

当我运行这个程序并检查哪些输入有效时,我发现即使我输入以' y'开头的单词。或者' n'代码不会输出错误消息,而是移动到程序的其余部分。此外,即使我输入了' Y'或者' N',它注册为无效响应。

2 个答案:

答案 0 :(得分:1)

您的代码只检查输入的第一个字符,因此难怪以yn开头的单词被认为是有效的。您可能想要比较整个字符串:

String response = keyboard.next();
while (!response.equalsIgnoreCase("y") && !response.equalsIgnoreCase("n")) {
  System.out.println("\nInvalid response. Try again.");
  response = keyboard.next();
} 
if (response.equalsIgnoreCase("n")) {
  System.out.println("\nCome back next time, " + customerName + ".");
} else {
  System.out.println("\nGreat! Let's get started.");
}

答案 1 :(得分:0)

问题是您只检查读取字符串的第一个字母:

  

char response = keyboard.next()。charAt(0)

你应该阅读整个字符串:

  

字符串响应= keyboard.next()

并在比较中使用它。为了确保“Y”和“N”也被视为有效,您可以使用String.equalsIgnoreCase(String)

  

while(!“Y”.equalsIgnoreCase(response)&&“N”.equalsIgnoreCase(response))

System.out.println("\nWould you like to order some coffee, " + customerName + "? (y/n)");

所以,将所有这些包装起来就像这样:

String response = keyboard.next();

while (!"Y".equalsIgnoreCase(response) && "N".equalsIgnoreCase(response)) {
   System.out.println("\nInvalid response. Try again.");
   response = keyboard.next();
} 

if ("N".equalsIgnoreCase(response)) {
   System.out.println("\nCome back next time, " + customerName + ".");
} else if ("Y".equalsIgnoreCase(response)) {
   System.out.println("\nGreat! Let's get started.");
}