我是Java的新手,並且創建了某種迷你遊戲,並且我希望玩家選擇是否要再次玩,我嘗試更改我的啓動布爾變量爲靜態類型並添加一些代碼行,但代碼似乎不起作用,每次我玩遊戲時,它都會問我是否要重播,但問題是即使我最後在控制檯鍵入「是」,遊戲似乎不會重新啓動。任何人都可以幫助我,我會非常感激,謝謝!字符串輸入在if-else語句中不起作用
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?
[我如何在Java中比較字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) –
NOOOOOOOOOOOOOOOOOOOOOOOOO不是可能重複' ==''再次:_( – Maroun
第100次我看到這個問題 –