我目前正在努力實現while循環在我的遊戲中,因爲它總是給我一個無限循環。我們的想法是繼續比賽,除了只有當用戶鍵入「-1」無限循環在搖滾紙剪刀循環遊戲
// declare variables
int player, computer;
int counter = 0;
// player input
System.out.println("Rock, Paper, Scissors!");
System.out.print("Enter 0 for paper, 1 for Scissors, or 2 for Rock (-1 to quit) : ");
player = sc.nextInt();
while (player != -1) {
// switch statement for player
switch (player) {
case 0:
System.out.println("Player picks Paper");
break;
case 1:
System.out.println("Player picks Scissors");
break;
case 2:
System.out.println("Player picks Rock");
break;
case -1:
System.exit(-1);
break;
default:
System.out.println("Invalid input");
}
// generate a random number for computer
Random randomGen = new Random();
computer = randomGen.nextInt(3);
// switch statement for computer
switch (computer) {
case 0:
System.out.println("Computer picks Paper");
break;
case 1:
System.out.println("Computer picks Scissors");
break;
case 2:
System.out.println("Computer picks Rock");
break;
default:
}
// output for each condition
if (player == 2 && computer == 1)
System.out.println("Player Wins!");
else if (player == 1 && computer == 0)
System.out.println("Player Wins!");
else if (player == 0 && computer == 2)
System.out.println("Player Wins!");
else if (computer == 1 && player == 0)
System.out.println("Computer Wins!");
else if (player == 0 && computer == 2)
System.out.println("Computer Wins!");
else if (player == 1 && computer == 2)
System.out.println("Computer Wins!");
else
System.out.println("Draw");
sc.close();
}
你有這條線重複:'否則,如果(球員== 0 &&電腦= = 2)'。如果第二次(否則)(電腦== 0 && player == 2)? –