所以我不久前使用Java制作了这个石头剪刀游戏,当我今天向朋友展示时,我发现了一个我忘了修理的小虫子。基本上,代码采用用户输入(即摇滚,纸张或剪刀),如果他们的输入不等于摇滚,纸张或剪刀,则主 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);
}
}
};
更新
由于这里好人的一些帮助,我想出了一些问题。我用过&&而不是|| (因为我最初使用&&& anyways -_-)这是愚蠢的,我使用"继续"语句而不是中断,我删除了gameRunning = false;
,然后我将userChoice
的方式与有效回复进行了比较。
而不是将它与Strings比如" 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);
}
}
};
谢谢大家!
答案 0 :(得分:1)
不要将gameRunning设置为false,不使用break,使用continue,这将忽略循环的其余部分并再次启动循环。
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
答案 1 :(得分:0)
有几个问题。将循环条件设置为false并且断开不能重新启动循环。另外,正如@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对象)。