0

strong text Very simple code should get inputs int from the user until no valid int information is entered and print out the min and max values after that. But I get two different problems:

First for some unknow reason the first "Enter a number:" shows after the first number is entered.

Second it crashes after no int information is entered even after the scanner.hasNextInt(); validation.

public static void minMaxChallenge() {
    Scanner scanner = new Scanner(System.in);
    int minValue = -1;
    int maxValue = -1;
    int counter = 0;
    boolean isAnInt = scanner.hasNextInt();

    while (true) {
        System.out.println("Enter a number: ");
        if (isAnInt) {
            int number = scanner.nextInt();

            if (counter == 0) {
                minValue = number;
                maxValue = number;
            } else if (number > maxValue) {
                maxValue = number;
            } else if (number < minValue) {
                minValue = number;
            }
            counter++;
        } else {
            System.out.println("Invalid Number Entered");
            break;
        }
        scanner.nextLine();
    }
    System.out.println("Your Maximum value entered is: " + maxValue);
    System.out.println("Your Minimum value entered is: " + minValue);
    scanner.close();
}
Adrest
  • 1
  • 1
    First, the `hasNextInt()` method waits for (keyboard) input if the Scanner has none. Second, the value of `isAnInt` never changes inside the `while` loop. – jaco0646 Oct 05 '22 at 19:19

0 Answers0