Jim Bones
Jim Bones

Reputation: 1

Try and Catch with JOption Does not work as expected

    int i=0;
    int c=0;
    int a=0;
    int b=0;
    String stringy;
    String input;

    do { //loop for value a
        try // try-catch to prevent program from crashing
        {
            stringy= JOptionPane.showInputDialog("Type a value for a or press q to quit:");                       
            if (stringy.equalsIgnoreCase("q")) System.exit(0); 
            a = Integer.parseInt(stringy);
            i++;               
         } catch (Exception e) {
               stringy= JOptionPane.showInputDialog("Error. Try Again! ");                 
         }  // end catch     
    } while(i==0); // end loop

the output produces a jOption input dialog box ("type a value...") and when i enter in a string or something that the system does not expect, it goes to the "catch"and pops out "error try again!" However, when i enter in anything into that, even if it is a number, it goes back to the ("type a value...") dialog box. I want it to read the input in the error box instead of jumping back to the first dialog box. Thank you for your help!

Upvotes: 0

Views: 60

Answers (3)

TEXHIK
TEXHIK

Reputation: 1398

You should take base input out of cycle, if you want to use input from catch(). And use break; clause unstead of while(i==0) and i++;

       stringy= JOptionPane.showInputDialog("Type a value for a or press q to quit: ");
       while(true)
       {
           if (stringy.equalsIgnoreCase("q")) System.exit(0);
           try {
               a = Integer.parseInt(stringy);
               break;
           } catch (Exception e) {
              stringy= JOptionPane.showInputDialog("Error. Try Again! ");
           }             
       }
       JoptionPane.showMessageDialog("Input accepted!");

And write your code in correct format please, you have commented '{' at the start of cycle.

Upvotes: 1

Revive
Revive

Reputation: 2248

How about adding a String for output.

    String input;
    String output = "Type a value for a or press q to quit: "

    do  //loop for value a        {
        try // try-catch to prevent program from crashing
        {
            stringy= JOptionPane.showInputDialog(output);                       
                            if (stringy.equalsIgnoreCase("q"))          
            {
              System.exit(0);
            }             
            a= Integer.parseInt(stringy);
            i++;               
         }
         catch (Exception e)
         {
               output= "Error. Try Again! ";                 

         }  

Upvotes: 0

Smutje
Smutje

Reputation: 18133

You obviously have to check the input of the second dialog too, similar to the following:

stringy = JOptionPane.showInputDialog("Error. Try Again! ");

if (stringy.equalsIgnoreCase("q")) {
    System.exit(0);
}

Upvotes: 0

Related Questions