Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<ul> <li><code>strTryDouble</code> was uppercased (<code>StrTryDouble</code>) in the declaration.</li> <li>Input and parsing were a bit unclear.</li> </ul> <p>The following works for me (JDK 6; changed lines marked <code>/***/</code>):</p> <pre><code>import java.io.*; import javax.swing.JOptionPane; public class MyType { public static void main(String[] args) { // declare class variables String strChoice, strTryString, strTryInt, strTryDouble; /***/ int choice, tryInt; double tryDouble; boolean done = false; boolean ok; /***/ // loop while not done while(!done) { try { strChoice = JOptionPane.showInputDialog(null, "What's my type\n\n\n1) String\n2) integer\n3) double\n4) Quit the program"); choice = Integer.parseInt(strChoice); /***/ switch(choice) { case 1: JOptionPane.showMessageDialog(null, "Correct, any input can be saved as a String."); break; case 2: strTryInt = JOptionPane.showInputDialog(null,"Enter an integer"); /***/ ok = true; try { /***/ tryInt = Integer.parseInt(strTryInt); } catch(NumberFormatException e) { /***/ ok = false; /***/ } JOptionPane.showMessageDialog(null, ok?"Correct.":"Not an integer"); /***/ break; case 3: strTryDouble = JOptionPane.showInputDialog(null,"Enter a double"); /***/ tryDouble = Double.parseDouble(strTryDouble); JOptionPane.showMessageDialog(null, "Correct."); break; case 4: done = true; JOptionPane.showMessageDialog(null, "The program will now close."); break; default: throw new NumberFormatException(); } } catch(NumberFormatException e) { JOptionPane.showMessageDialog(null,"Please enter a 1, 2, 3, or 4.","Error",JOptionPane.INFORMATION_MESSAGE); } } } } </code></pre> <p>To get the choice of type, <code>JOptionPane.showInputDialog</code> returns the string from the user, then <code>Integer.parseInt</code> parses it. </p> <p>To get the value, you use the same pattern: get a string, then parse it. Getting the string within each <code>case</code> takes care of the uninitialized variables.</p> <p>In case 2, I have added an example of how to check whether it was actually an integer and then proceed with code. In general, you can catch the exception and set a flag (<code>ok</code>) to process on. I only use this when the exceptions are how a function reports a normal condition (e.g., bad user input); for real errors, I let the exception propagate to a higher-level <code>catch</code> block.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload