1

在尝试验证用户响应以退出我的应用程序或重试(它是一个简单的游戏)时遇到问题?当游戏结束时,我询问用户是否要继续输入“y”表示是或“n”表示否退出。我如何验证他们的响应,所以如果它既不是 y 也不是 n 我显示错误消息并要求他们再次输入???

这似乎对我不起作用???

if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))

           System.out.println("Error enter y for yes and n for no");
            System.out.println("Would you like to play again (y/n):");
           choice = sc.next();
4

2 回答 2

2

只需更改

if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))

while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))

每次他们不选择字母“n”或“y”时,这将继续要求他们再输入一个字母。

if编辑:另外,您可能希望在(soon to be while) 语句中的代码周围加上括号。

于 2013-02-24T03:28:19.583 回答
0

没有任何完整的上下文,很难给出相关的答案。

if但是您已经可以在语句周围使用花括号来测试您的代码:

if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
  System.out.println("Error enter y for yes and n for no");
  System.out.println("Would you like to play again (y/n):");
  choice = sc.next();
}

实际上,使用您当前的代码,只有第一行:

System.out.println("Error enter y for yes and n for no");

是根据您的情况考虑的。

于 2013-02-24T03:24:55.143 回答