Is it possible to check for a NumberFormatException for input string: ""?
I tried to write my program so that if the user didn’t put in any values an error message would come out instead of NumberFormatException:
if(pasientNavnFelt.getText() == "" || pasientNrFeIt.getText() == "")
{
utskriftsområde.setText("ERROR, insert values");
}
if(pasientNavnFelt.getText() != "" || pasientNrFeIt.getText() != "")
{
// rest of code here if the program had values in it
}
I also tried with null:
if(pasientNavnFelt.getText() == null || pasientNrFeIt.getText() == null)
{
utskriftsområde.setText("ERROR, insert values");
}
if(pasientNavnFelt.getText() != null || pasientNrFeIt.getText() != null)
{
// rest of code here if the program had values in it
}
I still get:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
The program works fine if it has values.
Never compare Strings with
==.==checks that the two objects are the same, and not that the two objects have the same characters. Useequals()to compare strings.That said, to validate that a string is a valid Integer, you indeed need to catch the exception:
This is basic Java stuff. Read the Java tutorial over exceptions.