I am trying to create a GUI where the user has to enter an integer. If the user enters a non-integer, it prompts the GUI. I also want it to exit. When I get it to exit, I get this error:
Exception in thread "main" java.lang.NumberFormatException: null.
I am a bit of a noob and need some guidance :)
public class Generator
{
public static void main (String[] args)
{ String input = JOptionPane.showInputDialog("Enter Desired Analysis level");
int analysisLevel = Integer.parseInt(input);
try
{
if (analysisLevel >= 0)
{
System.out.println(analysisLevel);
}
else
{
input = JOptionPane.showInputDialog("Enter Desired Analysis level");
}
}
catch (Exception e)
{
System.out.println("Input was no number" + e);
System.exit(0);
}
System.exit(0);
}
}
The problem is that you left the one line that will likely cause an exception (int analysisLevel = Integer.parseInt(input);
) out of the try/catch block. You need to move it inside:
String input = JOptionPane.showInputDialog("Enter Desired Analysis level");
try
{
int analysisLevel = Integer.parseInt(input);
if (analysisLevel >= 0) {
System.out.println(analysisLevel);
} else {
input = JOptionPane.showInputDialog("Enter Desired Analysis level");
}
}
catch (Exception e)
{
System.out.println("Input was no number. " + e);
}
Additionally you do not need the System.exit(0);
's as the program will exit anyways, and using System.exit(0);
is generally not good practice.