問候堆棧溢出用戶,我今天晚上向你求助,幫助我創建了一個Java程序。我對Java比較陌生,所以請原諒我對這個話題的無知。我做了一個Java程序,這是一個「搖滾」「紙」「剪刀」遊戲,似乎有一個錯誤的陳述之一。Java - 嵌套的while循環
import java.util.Scanner;
public class TheAntlers {
public static void main(String[] args) {
int playerHumanWins = 0;
int playerComputerWins = 0;
int numberOfTies = 0;
int computerResult;
Scanner input = new Scanner(System.in);
while(true) {
String startGame;
String playerHuman;
String playerComputer = " ";
System.out.print("Do you want to play \"Rock\", \"Paper\", \"Scissors\"? (Y/N): ");
startGame = input.nextLine();
startGame = startGame.toUpperCase();
if(startGame.equals("N")) {
System.out.println("NO!");
break;
}
else if(! startGame.equals("Y")) {
startGame = startGame.toLowerCase();
System.out.println("Sorry, " + startGame + " is not a valid entry...");
}
while(startGame.equals("Y")) {
System.out.print("Please choose \"Rock\", \"Paper\", or \"Scissors\": ");
playerHuman = input.nextLine();
computerResult = (int)(Math.random() * 3);
playerHuman = playerHuman.toUpperCase();
if(computerResult == 1) {
playerComputer = "ROCK";
}
else if(computerResult == 2) {
playerComputer = "PAPER";
}
else if (computerResult == 3) {
playerComputer = "SCISSORS";
}
switch (playerHuman) {
case "ROCK" :
if(playerComputer.equals(playerHuman)) {
System.out.println("Tie you both picked \"ROCK\"");
numberOfTies++;
}
else if(playerComputer.equals("PAPER")) {
System.out.println("Computer wins!");
playerComputerWins++;
}
else {
System.out.println("You win, \"ROCK\" beats " + "\"" + playerComputer + "\"");
playerHumanWins++;
return;
}
break;
case "PAPER" :
if(playerComputer.equals(playerHuman)) {
System.out.println("Tie you both picked \"PAPER\"");
numberOfTies++;
}
else if(playerComputer.equals("ROCK")) {
System.out.println("You win, \"PAPER\" beats " + "\"" + playerComputer + "\"");
playerHumanWins++;
return;
}
else {
System.out.println("Sorry, the computer won!");
playerComputerWins++;
}
break;
case "SCISSORS" :
if(playerComputer.equals(playerHuman)) {
System.out.println("Tie you both picked \"SCISSORS\"");
numberOfTies++;
}
else if(playerComputer.equals("PAPER")) {
System.out.println("You win, \"SCISSORS\" beats " + "\"" + playerComputer + "\"");
playerHumanWins++;
return;
}
else {
System.out.println("Sorry, the computer won!");
playerComputerWins++;
}
break;
default:
playerHuman = playerHuman.toLowerCase();
System.out.println("Sorry, " + playerHuman + " is not a valid entry...");
break;
}
}
}
}
}
我面臨的問題與獲獎計算有關。當我運行該程序,我多次進入岩石,直到我贏了,輸出會你贏了,「ROCK」節拍「」,但與任何其他選項,我得到你贏了,「ROCK」擊敗「紙」
我的問題是,爲什麼我在玩搖滾時會得到空回調?
* 此外,如果你願意指出任何其他建議,以幫助新手,這將是偉大的。 *
更好的是if(computerResult == 0)playerComputer =「ROCK」; (computerResult == 1){ } playerComputer =「PAPER」; } else { playerComputer =「SCISSORS」; } –
不要忘記添加,如果你想要一個1到3之間的數字,你可以這樣做:1 +(int)Math.random()* 3; –
好點@AmirAfghani,雖然在這種情況下,0,1和2對大多數程序員來說是很自然的。 –