好吧,我想通过一些搜索找到它,但现在我有另一个问题 当弹出第二个框时,我点击“否”'第一个盒子仍然运行,如果我取消它,我会收到一个错误。我做错了什么?
import javax.swing.*;
import java.util.*;
import java.util.Scanner;
public class RPS {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String input;
int user;
int computer;
while (true){//here we go
input = JOptionPane.showInputDialog("What'll it be? Rock, paper, or scissors?\n" +
"1 for rock, 2 for paper, and 3 for scissors: ",JOptionPane.YES_NO_OPTION);
user = Integer.parseInt(input);
Random randomnum = new Random ();
computer = randomnum.nextInt(3);
if (user == 1 && computer == 0){System.out.println ("You played Rock! You have tied");
JOptionPane.showMessageDialog(null, "Tie!");}
else if (user == 1 && computer == 1){System.out.println ("You have played Rock! You have lost");
JOptionPane.showMessageDialog(null, "Paper beats rock. You lose!");}
else if (user == 1 && computer == 2){System.out.println ("You have played Rock! You have won");
JOptionPane.showMessageDialog(null, "Rock beats scissors. You win!");}
else if (user == 2 && computer == 0){System.out.println ("You have played Paper! You have won");
JOptionPane.showMessageDialog(null, "Paper beats rock. You win!");}
else if (user == 2 && computer == 1){System.out.println ("You have played Paper! You have tied");
JOptionPane.showMessageDialog(null, "Tie!");}
else if (user == 2 && computer == 2){System.out.println ("You have played Paper! You have lost");
JOptionPane.showMessageDialog(null, "Scissors beats paper. You lose!");}
else if (user == 3 && computer == 0){System.out.println ("You have played Scissors! You have lost");
JOptionPane.showMessageDialog(null, "Rock beats Scissors. You lose!");}
else if (user == 3 && computer == 1){System.out.println ("You have played Scissors! You have won");
JOptionPane.showMessageDialog(null, "Scissors beats paper. You win!");}
else if (user == 3 && computer == 2){System.out.println ("You have played Scissors! You have tied");
JOptionPane.showMessageDialog(null, "Tie!");}
int n = JOptionPane.showConfirmDialog(null,"Would you like to play again?", "Confirmation",JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null,"Let's start");
} else {
JOptionPane.showMessageDialog(null,"Goodbye");
}
}
}
}
答案 0 :(得分:0)
在return;
之后加上JOptionPane.showMessageDialog(null,"Goodbye");
语句。否则它不知道结束while循环。
如果您选择立即取消,当您按取消时也会发生错误。这是因为parseInt不知道如何读取结果输入。您应该检查showInputDialog的返回值以查看它的有效输出。我建议检查" 1"," 2"或" 3" (或"摇滚","纸张"或" scizzors")而不是使用parseInt,然后如果它不匹配它们中的任何一个来以及某种错误消息。