[英]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) ^
变量选择可能尚未初始化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 tryDouble;
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. 如果showInputDialog抛出,则未设置“选择”。
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)
{
您应该在try块之前初始化选择变量,因为您在catch中引用了该变量,在某些情况下,如果在选择初始化初始化之前引发了异常,则可变选择将未被初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.