Home > database >  Why do I have to enter two integer at first to proceed to the iteration? hasInt(), nextLine(), nextI
Why do I have to enter two integer at first to proceed to the iteration? hasInt(), nextLine(), nextI

Time:03-18

When I attempted to run this, I have to enter 2 integers and enters for the loop to move to the next iteration but it does not happen from the second loop? What is the reason and what is the logic to fix this?

import java.util.Scanner;

public class MinAndMaxInputChallenge {
    public static void main(String[] args) {
        int max = 0;
        int min = 0;
        int number;
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("Enter number ");
            number = scanner.nextInt();
            boolean hasInt = scanner.hasNextInt();
            scanner.nextLine();
            if (hasInt) {
                if (number > max)
                    max = number;
                else if (number < min)
                    min = number;
            } else break;
        }
        System.out.println("Max = "   max   " Min = "   min);
        scanner.close();
    }
}

Code & Ouput

CodePudding user response:

you code logic is just a little off. Check first if the kb has an int in it's buffer. If it does, read it in, consume eol, set min or max and then break out of the while loop

import java.util.Scanner;

public class MinAndMaxInputChallenge {
    public static void main(String[] args) {
        int max = 0;
        int min = 0;
        int number;
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("Enter number ");
            
            boolean hasInt = scanner.hasNextInt();
            
            if (hasInt) {
                number = scanner.nextInt();
                scanner.nextLine();
                if (number > max)
                    max = number;
                else if (number < min)
                    min = number;
                break;
            } 
        }
        System.out.println("Max = "   max   " Min = "   min);
        scanner.close();
    }
}
  • Related