Hello I’m a beginning programming Student and I am practicing using loops to validate input. Unfortunately, the loop works but skips the inner loop entirely… I get now error message or prompt…
Here is my code: [I BORROWED IT FROM AN ANSWER ON THIS SITE ABOUT VALIDATING INPUT SO I COULD TEST IT.]
import java.util.Scanner;
public class ValidationTest
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number!");
while (!sc.hasNextInt())
{
System.out.println("That's not a number!");
sc.next(); // this is important!
}
number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);
}
}
The inner loop :
only check if your input is not a number, if you input -123, the function
!sc.hasNextInt()is false so it’ll skip the loop, if you want to check the number is negative, add this check after the assign number value:You don’t have to make another loop for checking the number is negative or not because of the first loop had it, and
do...whileloop will make sure you have to run the loop at least one time