Reputation: 473
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.
Upvotes: 0
Views: 3703
Reputation: 8586
Your second if condition is wrong. You're trying to say, if there's a null, error, else do something. You're saying if there's a null error, then if either of them is not null, do the rest. The two character change is change the second "||" to a "&&". But what you probably want is actually:
if(pasientNavnFelt.getText() == null || pasientNrFeIt.getText() == null)
{
utskriftsområde.setText("ERROR, insert values");
}
else
{ <rest of code here if the program had values in it>}
Upvotes: 0
Reputation: 691755
Never compare Strings with ==
. ==
checks that the two objects are the same, and not that the two objects have the same characters. Use equals()
to compare strings.
That said, to validate that a string is a valid Integer, you indeed need to catch the exception:
try {
int i = Integer.parseInt(s);
// s is a valid integer
}
catch (NumberFormatException e) {
// s is not a valid integer
}
This is basic Java stuff. Read the Java tutorial over exceptions.
Upvotes: 2
Reputation: 14853
Try:
if( pasientNavnFelt.isEmpty() || pasientNrFeIt.isEmpty()) {
utskriftsområde.setText("ERROR, insert values");
}
else {
...
}
Upvotes: 1