默认在 Java Switch 语句中不起作用

Default not working in Java Switch Statement

当用户输入一个未选择的选项时,我希望他们收到一条错误消息,然后让他们重试。但是我的 'default :' 不允许我这样做。有什么原因吗?

非常感谢:)

while( i != 1 ) {

String input6 = JOptionPane.showInputDialog("Please select the program you would like to run:\n1) Rock, Paper, Scissors Game\n2) Rules About The Game\n3) Exit This Program");
int input3 = Integer.parseInt(input6);


switch(input3)
{
  case 1 :
  { 
// Deleted for sake of irrelevance in question
  }
      break;
    case 2 :
    {
        JOptionPane.showMessageDialog(null,"You have selected the game's rules.\nOpening the rules...\nLoaded successfully!  Please press OK.");
        JOptionPane.showMessageDialog(null,"Here are the rules for the game:\nIn total, there are 3 rounds for this game, including Ties.\nPaper vs Rock => Paper is the Winner.  Add 1 to the winner.\nPaper vs Scissors => Scissors is the Winner.  Add 1 to the winner.\nRock vs Scissors => Rock is the Winner.  Add 1 to the winner.\nRock vs Rock => Tie.  No score.\nScissors vs Scissors => Ties.  No score.\nPaper vs Paper => Tie.  No score.");
    }
    break;
    case 3 :
    {
        JOptionPane.showMessageDialog(null,"You have selected to exit the program.  Closing the program... please press OK.");
        System.exit(0);
    }
        break;
    default :
    {
      JOptionPane.showMessageDialog(null,"You entered an invalid operation.  Please select 1, 2, or 3.");
    }
    {
    i=1;
    }     
  }
}

当您转换输入 String to int 时,只要输入不是有效数字,就会出现错误。所以程序甚至没有达到 switch 语句。要解决此问题,您有两种选择:

  1. 将您的输入限制为仅 int 这些可以不是 1,2,3。但它们必须是 int

  2. 大小以内的数字
  3. try-catch 块中包围您的 String to int 转换,如果您得到 NumberFormatException

    则显示错误
    try {  
        int input3 = Integer.parseInt(input6);
    
        //....
        //switch block
        //..
    }
    catch(NumberFormatException nfe){
        JOptionPane.showMessageDialog(null,"You entered an invalid operation.  Please select 1, 2, or 3.");
        continue;   // go to beginning of loop
    }
    

编辑:在 catch 块中添加 continue,以在错误消息后循环回到输入提示。

问题是默认方法中的 i=1。在默认情况下执行并停止循环。其次关于解析 int 错误使用 try catch around parseint 以便用户输入仅限于 int 并且您的程序运行时 error.Have 看一下这个 link