So I'm trying to use my variable n after my try-catch, but I can't because my compiler is complaining that my n
variable 'might not have been initialized'. How can I fix this? Here is the code:
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
}
You should initialize n.
int n = 0;
...
You merely need to initialize it beforehand:
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
}
On a side note, you don't need to have a validInput
variable at all. If you use continue
and break
statements, you also won't need to initialize the variable:
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.