我正在尝试使用 Random().nextInt() 函数获取随机数。我不知道这是否正确,或者我的逻辑是否混乱或阅读不正确。此外,for 循环也没有按照预期的方式工作。你能帮忙吗?自从我们上个月开始使用 Java 以来,我一直在努力完成课堂作业。
//DECLARE VARIABLES
String rounds, userChooses;
Random computerChooses = new Random();
int round = 1;
int userChoice = 0;
final int ONE = 1;
final int TWO = 2;
final int THREE = 3;
int computerChoice = computerChooses.nextInt(3) + 1;
//ASK USER FOR NUMBER OF ROUNDS
rounds = JOptionPane.showInputDialog(null, "How many rounds do you want to play?");
round = Integer.parseInt(rounds);
//TRACK NUMBER OF ROUNDS
for (int x = 1; x <= round; x++) {
JOptionPane.showMessageDialog(null, "This is round " + x + ".");
//CREATE THE INPUT FOR THE USER
try {
//START GAME
userChooses = JOptionPane.showInputDialog(null, "Enter 1)rock, 2)paper, or 3)scissors!");
userChoice = Integer.parseInt(userChooses);
if (userChoice > 3 || userChoice < 1) {
throw new Exception();
}
} catch (Exception ex) {
JOptionPane.showInputDialog(null, "That wasn't a number!", "Error!", JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(null, "You have not entered correct number! Terminating program!");
System.exit(0);
}
if (userChoice == ONE) {
if (computerChoice == ONE) {
JOptionPane.showMessageDialog(null, "You tied the computer.\nYou chose: rock\nComputer chose: rock");
} else if (computerChoice == TWO) {
JOptionPane.showMessageDialog(null, "You lost!\nYou chose: rock\nComputer chose: paper");
} else if (computerChoice == THREE){
JOptionPane.showMessageDialog(null, "You won!\nYou chose: rock\nComputer chose: scissors");
}
} else if (userChoice == TWO) {
if (computerChoice == ONE) {
JOptionPane.showMessageDialog(null, "You won!\nYou chose: paper\nComputer chose: rock");
} else if (userChoice == TWO) {
JOptionPane.showMessageDialog(null, "You tied!\nYou chose: paper\nComputer chose: paper");
} else if (userChoice == THREE) {
JOptionPane.showMessageDialog(null, "You lost!\nYou chose: paper\nComputer chose: scissors");
}
} else if (userChoice == THREE) {
if (computerChoice == ONE) {
JOptionPane.showMessageDialog(null, "You lost!\nYou chose: scissors\nComputer chose: rock");
} else if (computerChoice == TWO) {
JOptionPane.showMessageDialog(null, "You won!\nYou chose: scissors\nComputer chose: paper");
} else if (computerChoice == THREE) {
JOptionPane.showMessageDialog(null, "You tied!\nYou chose: scissors\nComputer chose: scissors");
}
}
}
}
每次我选择某些东西时,它都会说计算机总是选择摇滚选项。任何的想法?