Search code examples
javaswitch-statementdefault

Default not working in Java Switch Statement


When a user enters in an option other than one selected, I'd like them to be given an error message, and then have them try again. However my 'default :' is not allowing me to do so. Any reason why?

Many thanks :)

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;
    }     
  }
}

Solution

  • The error you are getting is when you are converting input String to int whenever input is not a valid number. So the program is not even reaching upto switch statement. To fix this you have two options:

    1. Restrict your input to only int these can be other than 1,2,3. But they have to be number within size of int

    2. Surround your String to int conversion in try-catch block and show error if you get 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
      }
      

    EDIT: Add continue in catch block, to loop back to input prompt after the error message.