Using Switch and Try Statement to Validate user Input
I've been working on this for a little while and it won't compile. It gives me an error saying
variable choice might not have been initialized switch(choice) ^
but I have that variable set in the program. So I don't know what the problem is? Is it really something else that's keeping this from compiling?
import java.io.*;
import javax.swing.JOptionPane;
public class MyType
{
public static void main(String[] args)
{
String strChoice = "", strTryString, strTryInt, strTryDouble;
Integer choice, tryInt;
double tryDoubl开发者_如何学Goe;
boolean done = false;
while(!done)
{
try
{
String answer = JOptionPane.showInputDialog(null, "What's my type\n\n\n1) String\n2) integer\n3) double\n4) Quit the program");
choice = Integer.parseInt(strChoice);
//test for valid codes 1, 2, 3, or 4
if (choice<1 || choice>4) throw new NumberFormatException();
else done = true;
}
catch(NumberFormatException e)
{
JOptionPane.showInputDialog(null, "Please enter a 1, 2, 3, or 4", "Error", JOptionPane.INFORMATION_MESSAGE);
switch(choice)
{
case 1:
JOptionPane.showMessageDialog(null, "Correct, any input can be saved as a String");
break;
case 2:
JOptionPane.showMessageDialog(null, "Correct!");
tryInt = Integer.parseInt(strChoice);
break;
case 3:
JOptionPane.showMessageDialog(null, "Correct!");
tryDouble = Integer.parseInt(strChoice);
break;
case 4:
done = true;
JOptionPane.showMessageDialog(null, "Exit.");
System.exit(0);
break;
default: throw new NumberFormatException();
}
}
}
}
}
If the showInputDialog throws, then 'choice' is not set.
try
{
String answer = JOptionPane.showInputDialog(null, "What's my type\n\n\n1) String\n2) integer\n3) double\n4) Quit the program");
choice = Integer.parseInt(strChoice);
//test for valid codes 1, 2, 3, or 4
if (choice<1 || choice>4) throw new NumberFormatException();
else done = true;
}
catch(NumberFormatException e)
{
you should iniatialize the choice variable before try block, as you are referencing it in catch which in some case if the exception is thrown before initialization of choice happining then the varaible choice will be uninitialized.
精彩评论