Reputation: 333
I have code to check for non numbers but also wish to include a check for negative numbers. If the number is negative or not a number, they have to re-enter info. I tried putting an if(depValue < 0)....
after try{
and before catch
but that didn't work. It doesn't make sense to me if I were to put the if statement after the while loop.
String depIn = "";
BufferedReader depositInput = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.print("Amount to deposit: ");
depIn = depositInput.readLine();
double depValue = 0.00;
try{
depValue = Double.parseDouble(depIn);
break;
}
catch(NumberFormatException ne){
System.out.println("You did not enter a number!");
}
}
Upvotes: 1
Views: 193
Reputation: 533870
You can break out of the loop when you have the number you need.
double depValue;
while(true){
System.out.print("Amount to deposit: ");
depIn = depositInput.readLine();
try {
if ((depValue = Double.parseDouble(depIn)) > 0)
break;
System.out.println("The number needs to be positive!");
} catch(NumberFormatException ne) {
System.out.println("You did not enter a number!");
}
}
Upvotes: 1
Reputation: 35106
Put it in the same try catch block, and just display the error message from the caught NumberFormatException
try{
depValue = Double.parseDouble(depIn);
if (depValue < 0) throw new NumberFormatException("Negative value not acceptable!");
break;
}
catch(NumberFormatException ne){
ne.printStackTrace();
}
Upvotes: 0