Reputation: 143
In my program I get the value of JTextField
and parse into an integer:
String string = jtext.getText();
int stringval = Integer.parseInt(str);
My question is how to I'm a able to check if the value was parsed into an integer? I tried this, but it didn't hold the results I wished to accomplished and I received errors.
if(str == null)
{
JOptionPane.showMessageDialog(null, "Integer not parsed", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
Upvotes: 1
Views: 62
Reputation: 1937
If it wasn't able to be parsed into an int it would throw an exception.
Try using a try catch statement
boolean tryParseInt(String value)
{
try
{
Integer.parseInt(value);
return true;
} catch(NumberFormatException nfe)
{
return false;
}
}
You could use it like this
if(tryParseInt(myInput))
{
Integer.parse(myInput);
}
or if you want to do it without a method
int stringval;
bool success = true;
try
{
stringval = Integer.parseInt(str);
}
catch (NumberFormatException nfe)
{
success = false;
JOptionPane.showMessageDialog(null, "Integer not parsed", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
if (success)
{
//do whatever
}
Hope that helps
Upvotes: 3