所以我不久前使用Java制作了这个剪刀石头布游戏,今天当我向我的 friend 展示它时,我发现了一个我忘记修复的小错误。基本上,代码接受用户输入(即石头、剪刀、布),如果他们的输入不等于石头、剪刀、布,则主 while 循环将被破坏,游戏将停止。
我怎样才能做到这一点,以便它不仅可以打破循环,而且还可以重新启动它?我想这样做,以便当有人给出无效输入时,它会自动重新启动,以便播放器不需要重新运行程序。
这是我的main类的代码:
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();
if(userChoice != "rock" || userChoice != "paper" || userChoice != "scissors") {
System.out.println("'" + userChoice + "'" + " is not a valid choice.");
System.out.println("Please choose between rock, paper, or scissors.");
gameRunning = false;
break;
// this is where I want to restart the function
}
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);
}
}
};
更新
感谢这里好心人的帮助,我解决了一些问题。我用 && 而不是 || (这很愚蠢,因为我最初使用了&& -_-),我使用了“继续”语句而不是break,我删除了gameRunning = false;
,并且我改变了userChoice<的方式
与有效响应进行比较。
我没有将其与“rock”和“paper”等字符串进行比较,而是创建了一个数组
(String validChoices[] = {"rock", "paper", "scissors"};
) 保存有效响应。然后我将 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,这将忽略循环的其余部分并再次开始循环。
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
关于java - 如果给出无效响应,请重新运行 main 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35466772/