Java 如果给出无效响应,是否重新运行main方法?
不久前,我用Java制作了这个石头剪刀布游戏,我发现了一个小错误,今天我给朋友看的时候忘了修复。基本上,代码接受用户输入(即石头、布或剪刀),如果他们的输入不等于石头、布或剪刀,则主while循环被中断,游戏停止 我如何使它不仅中断循环,而且重新启动循环?我想这样做,当有人给出无效输入时,它会自动重新启动,这样播放器就不需要重新运行程序 以下是我的主要课程的代码: 更新 多亏了这里善良的人们的帮助,我解决了一些问题。我使用了&&而不是| |(这是愚蠢的,因为我最初使用了&&无论如何-|-),我使用了“continue”语句而不是break,我删除了Java 如果给出无效响应,是否重新运行main方法?,java,loops,while-loop,main,restart,Java,Loops,While Loop,Main,Restart,不久前,我用Java制作了这个石头剪刀布游戏,我发现了一个小错误,今天我给朋友看的时候忘了修复。基本上,代码接受用户输入(即石头、布或剪刀),如果他们的输入不等于石头、布或剪刀,则主while循环被中断,游戏停止 我如何使它不仅中断循环,而且重新启动循环?我想这样做,当有人给出无效输入时,它会自动重新启动,这样播放器就不需要重新运行程序 以下是我的主要课程的代码: 更新 多亏了这里善良的人们的帮助,我解决了一些问题。我使用了&&而不是| |(这是愚蠢的,因为我最初使用了&&无论如何-|-),我使
gameRunning=false代码>,我改变了将userChoice
与有效响应进行比较的方式
我创建了一个数组,而不是将其与“rock”和“paper”等字符串进行比较
(String validChoices[]={“rock”、“paper”、“剪刀”};
)保存有效响应。然后我将userChoice
与数组的索引进行了比较
这是我的新代码:
public class rps {
public static void main(String []args){
boolean gameRunning = true;
while(gameRunning) {
System.out.println("Do you choose rock, paper, or scissors?");
UserChoice userInput = new UserChoice();
String userChoice = userInput.userDecide();
String validChoices[] = {"rock", "paper", "scissors"};
if(!userChoice.equals(validChoices[0]) && !userChoice.equals(validChoices[1]) && !userChoice.equals(validChoices[2])) {
System.out.println("'" + userChoice + "'" + " is not a valid choice.");
System.out.println("Please choose either rock, paper, or scissors.");
continue;
}
System.out.println("You threw: " + userChoice);
ComputerInput computerChoice = new ComputerInput();
String computerInput = computerChoice.computerDecide();
System.out.println("Computer threw: " + computerInput);
CompareChoices compareResults = new CompareChoices();
gameRunning = compareResults.compare(userChoice, computerInput);
}
}
})
谢谢大家 不要将gameRunning设置为false,要不使用break,请使用continue,这将忽略循环的其余部分并再次启动循环
有几个问题。将循环条件设置为false和breaking将无法重新启动循环。此外,正如@resueman所暗示的那样。使用.equals()而不是==来比较字符串。我的建议是将错误检查放在另一个while循环中
while(!userChoice.equals("rock") && !userChoice.equals("paper") && !userChoice.equals("scissors")) {
System.out.println("Your choice was invalid, try again");
userChoice = userInput.userDecide();
}
另外,您可能应该在while循环之外声明一些内容(我想到的是您的ComputerInput、UserInput和CompareChoices对象)。为了避免不可避免的后续问题,请阅读以下内容:您的if语句是错误的。它应该使用&&而不是| |。你现在的表达永远都是真的。好吧,那部分用得上。当我输入一个无效响应(即我使用了香蕉)时,它会重新启动循环并再次询问我。但是当我输入一个有效的响应(即rock)时,它仍然会说这是一个无效的响应,并重新启动循环。非常感谢!!!!我算出了&&并继续它的一部分,但我真正的问题是比较运算符。而不是我使用了.equals方法。现在它就像一个符咒!
while(!userChoice.equals("rock") && !userChoice.equals("paper") && !userChoice.equals("scissors")) {
System.out.println("Your choice was invalid, try again");
userChoice = userInput.userDecide();
}