Problems with While loop execution
I have a problem with the second while loop shown below. The guidelines I was given was that my variable 'speed' cannot be a negative number. So I make this a condition in my while loop. If a negative number is entered, it prompts the user to enter a number greater than or equal to 0. That's all fine and dandy...my problem is that if the user inputs a non-negative number it is ignored. Am I missing something??
Here is the part of code in question:
Code:
public class Demo {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter the speed: ");
while(!in.hasNextInt()){
System.out.println("Error: That was not a number!" + " '" + in.nextLine() +
"'" + "\nEnter the speed: ");
}
int speed = in.nextInt();
while (speed < 0) {
System.out.println("Enter a number greater or equal to 0: " + in.nextLine());
}
SpeedHours speedHours = new SpeedHours(speed);
System.out.println("The speed is: " + speedHours.getSpeed());
}
}
Any advice is greatly appreciated!