【发布时间】:2020-02-16 13:57:44
【问题描述】:
我试图弄清楚为什么我的 main 方法中的 while 循环被忽略了,即使我没有输入“退出”。该程序应该接受用户的输入(转换为 int),让计算机生成一个随机 int(石头、纸或剪刀),比较两个 int,打印出答案,然后从头再来,直到“退出" 或任何其他无法识别的输入(不是石头、纸或剪刀)。
例如:UserInput = rock;输出:再见!!! (while 循环只是跳过,直接进入 if 循环,即使“userInput”(转换为 int 1)不等于“quit”(转换为 int 0)。 试图修复它,如果UserInput =“rock”(转换为1),计算机随机生成“paper”(转换为2),输出将是“paper”获胜。
我已经尝试解决这个问题好几个小时了,感谢任何帮助,谢谢。
package rockPaperScissors;
import java.util.*
public class RockPaperScissors {
public static final int quit = 0;
public static final int rock = 1;
public static final int paper = 2;
public static final int scissors = 3;
static Scanner console = new Scanner(System.in);
public static void main(String [] args) {
//gets userHand from user as int
int userHand = promptUserForHand();
while(userHand != quit) {
//gets computerHand from the computer(random) as int
int computerHand = generateRandomHand();
//compares userHand to computerHand, determines the winner
String winner = determineWinner(userHand, computerHand);
//prints out the winner
System.out.println("The winner is the: " + winner);
//starts the next round
userHand = promptUserForHand();
}
//if userHand equals quit, stop program and say goodbye
if(userHand == quit) {
System.out.println("Goodbye!!!");
console.close();
}
}
public static int promptUserForHand() {
//gets userInput from user
System.out.println("Please input either rock, paper, scissors (or enter quit to stop)");
String userInput = console.next();
//converts String into int, so userHand and computerHand can be compared
int userHand = 0;
if(userInput == "rock" || userInput == "Rock" || userInput == "r") {
userHand = rock;
}
else if(userInput == "paper" || userInput == "Paper" || userInput == "p") {
userHand = paper;
}
else if(userInput == "scissors" || userInput == "Scissors" || userInput == "s"){
userHand = scissors;
}
else {
userHand = quit;
}
return userHand;
}
//generates computerHand from computer(randomly chooses either rock(1), paper(2), or scissors(3))
public static int generateRandomHand() {
Random r = new Random();
int computerHand = r.nextInt(4) + 1;
return computerHand;
}
//compares userHand to computerHand to determine the winner
public static String determineWinner(int userHand, int computerHand) {
String winner = " ";
if(userHand == 1 && computerHand == 2) {
winner = "Computer!!!";
}
else if(userHand == 1 && computerHand == 3) {
winner = "User!!!";
}
else if(userHand == 2 && computerHand == 1) {
winner = "User!!!";
}
else if(userHand == 2 && computerHand == 3) {
winner = "Computer!!!";
}
else if(userHand == 3 && computerHand == 1) {
winner = "Computer!!!";
}
else if(userHand == 3 && computerHand == 2) {
winner = "User!!!";
}
else {
winner = "Tie!!!";
}
return winner;
}
}
【问题讨论】:
标签: java while-loop