所以我尝试在try-catch之后使用我的变量n,但我不能,因为我的编译器抱怨我的n
变量'可能没有被初始化'。我怎样才能解决这个问题?这是代码:
public static void main(String[] args) {
int n;
boolean validInput = false;
String scanner;
while (!validInput) {
scanner = JOptionPane.showInputDialog("Please insert an integer:");
try {
n = Integer.parseInt(scanner);
validInput = true;
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(null, "Not an integer!");
validInput = false;
}
}
System.out.println(n); //I can't use the n even though I give it a value inside my try-catch
}
答案 0 :(得分:0)
你应该初始化n。
int n = 0;
...
答案 1 :(得分:0)
您只需要事先对其进行初始化:
public static void main(String[] args) {
int n = 0;
boolean validInput = false;
String scanner;
while (!validInput) {
scanner = JOptionPane.showInputDialog("Please insert an integer:");
try {
n = Integer.parseInt(scanner);
validInput = true;
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(null, "Not an integer!");
validInput = false;
}
}
System.out.println(n); //I can't use the n even though I give it a value inside my try-catch
}
在旁注中,您根本不需要validInput
变量。如果您使用continue
和break
语句,则您也不需要初始化变量:
public static void main(String[] args) {
int n;
String scanner;
while (true) {
JOptionPane.showInputDialog("Please insert an integer:");
try {
n = Integer.parseInt(scanner);
break;
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(null, "Not an integer!");
continue;
}
}
s.close();
System.out.println(n);
}