1

I want to scan in an integer and put it in a while loop so that if an invalid entry is entered the program will ask to enter another integer but when I run this it won't allow me to enter and new integer and just prints invalid entry multiple times.

do {
    System.out.println("Maximum number of Students:");
    if(input.hasNextInt()) {
        maxstudents = input.nextInt();
        if (maxstudents > 0) {
            break;
        }
    } else {
        System.out.println("Invalid entry");
    }
} while(true);
Adam
  • 2,927
  • 14
  • 25

3 Answers3

3

Change the else to :

  else {
    System.out.println("Invalid entry");
    input.nextLine();
  }

So on an invalid input you need to move the cursor to the next line so that you can accept the input again.

Nicholas K
  • 14,118
  • 7
  • 25
  • 49
0

@Nicholas K is right. But I offer you to add another warning message for situation with negative integer and move this code into separate method.

public static int getMaxStudents(Scanner scan) {
    do {
        System.out.print("Maximum number of Students: ");

        if (scan.hasNextInt()) {
            int maxStudents = scan.nextInt();

            if (maxStudents > 0)
                return maxStudents;
        }

        System.out.println("Enter a valid positive integer number");
        scan.nextLine();    // <-- this is mandatory
    } while (true);
}
oleg.cherednik
  • 12,764
  • 2
  • 17
  • 25
0
do {
        System.out.println("Maximum number of Students:");
            if(input.hasNextInt()) {
                maxstudents = input.nextInt();
                    if (maxstudents > 0) {
                        break;
                    }
            }
            else {
                System.out.println("Invalid entry:"+scanner.next());
            }
    }while(true);
Md Mahamudul Hasan
  • 2,151
  • 2
  • 12
  • 20