我是 Java 新手,我创建了某种迷你游戏,我希望玩家选择是否要再次玩,我尝试将我的 start 布尔变量更改为静态类型并添加一些代码行,但是代码似乎不起作用,每次我玩游戏时,它都会问我是否要重玩,但问题是即使我最后在控制台输入“是”,游戏也没有'似乎没有重新启动。谁能帮帮我,我将不胜感激,谢谢!
import java.util.Random;
import java.util.Scanner;
//Rocks, papers, scissors game complied by William To.
public class RockPaperScissor {
static int gamePlays = 0;
static boolean start = true;
public static void main(String[] args) {
while (start){
@SuppressWarnings("resource")
Scanner userInput = new Scanner(System.in);
Random comOutput = new Random();
System.out.println("Do you choose rock, paper or scissor?");
String userChoice = userInput.nextLine();
int comChoice = comOutput.nextInt(2);
switch (userChoice){
case "rock":
if(comChoice == 0){
System.out.println("I choose rock too! That's a draw!");
} else if(comChoice == 1){
System.out.println("I choose paper! I win!");
} else {
System.out.println("I choose scissor! You win!");
}
break;
case "paper":
if(comChoice == 0){
System.out.println("I choose rock! You win!");
} else if(comChoice == 1){
System.out.println("I choose paper too! That's a draw!");
} else {
System.out.println("I choose scissor! I win!");
}
break;
case "scissor":
if(comChoice == 0){
System.out.println("I choose rock! I win!");
} else if(comChoice == 1){
System.out.println("I choose paper! You win!");
} else {
System.out.println("I choose scissor too! That's a draw!");
}
break;
default :
System.out.println("I don't think that's an option.");
break;
}
gamePlays++;
System.out.println("You've played " + gamePlays + " games.");
//BELOW IS THE PART I want to ask, what's wrong?
System.out.println("Do you want to play again?");
String playAgain = userInput.next();
if (playAgain == "yes"){
System.out.println("Restarting game...");
start = true;
} else if (playAgain == "no") {
System.out.println("Quitting game.");
start = false;
}
}
}
}
Eclipse 的打印输出:
Do you choose rock, paper or scissor?
rock **//my input**
I choose paper! I win!
You've played 1 games.
Do you want to play again?
yes **//my input**
Do you choose rock, paper or scissor?
paper **//my input**
I choose paper too! That's a draw!
You've played 2 games.
Do you want to play again?
no **//my input**
Do you choose rock, paper or scissor?