Reputation: 81
I am trying to make a simple method which test to see if a provide String contains only numbers, to do this I am trying to use try and catch (just learnt it and I would like to practise putting it to use) where I try to parseInt() the given String and if there's an error (not a number) then it will catch it and return false;
public boolean checkNumber(String s){
try(Integer.parseInt(s)){
return true;
}
catch(Exception E){
return false;
}
}
It says I have a misplaced constructor.
Upvotes: 0
Views: 3588
Reputation: 97
syntax error
try {
Integer.parseInt(s);
} catch(Exception e) {
return false;
}
return true;
Upvotes: 1
Reputation: 762
That's not the correct syntax for try. Use
try
{
Integer.parseInt(s);
return true;
}
catch (Exception ex)
{
return false;
}
Upvotes: 1
Reputation: 20073
Catch the correct exception and move the try check into the block rather than in brackets.
try {
Integer.parseInt(s);
return true;
}
catch(NumberFormatException e){
return false;
}
Upvotes: 6