I'm trying to verify user input for a school assignment, wherein a negative number or anything except for a double causes the loop to retry. The rest of the code does some simple arithmetic with the input and that's all functional so I didn't include it, but here is the input verification I have so far. Right now inputting a negative number does what I want it to do, but entering a different character causes in infinite loop of
"null
Enter wall height (feet): "
Why isn't the !scnr.hasNextDouble() exception throwing, and why is it repeating infinitely, when the negative number exception is working as intended? I'd very much appreciate any help I could get on this, thank you.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double wallHeight = 0.0;
double wallWidth = 0.0;
double wallArea = 0.0;
double gallonsPaintNeeded = 0.0;
final double squareFeetPerGallons = 350.0;
// Implement a do-while loop to ensure input is valid
do {
try {
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) {
throw new Exception("Enter positive number");
}
else if (!scnr.hasNextDouble()) {
throw new Exception("Invalid input.");
}
}
catch(Exception excpt){
System.out.println(excpt.getMessage());
}
}while(wallHeight <= 0 || !scnr.hasNextDouble());