Don't want the scanner to initalize

Viewed 36

I'm trying to solve an exercise in which I have to read 10 numbers with the scanner and find out the max and min value. I was able to make that with a for loop asking for 10 values, but, when I run the program, the scanner asks for a value that is not required in the loop. That's my code right now:

import java.util.Scanner;

public class Exercicio4 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int max = n;
        int min = n;
        for (int i = 0; i < 9; i++) {
            System.out.println("Digite um número: ");
            n = scan.nextInt();
            if  (n > max)
                max = n;
            if (n < min)
                min = n;
        }

        System.out.println("O maior número é: " + max);
        System.out.println("O menor número é: " + min);
        scan.close();
    }
}
1 Answers

You don't have to ask the user for an initial value for max and min.
Set max to the lowest possible value, i.e. Integer.MIN_VALUE. It will always be lower than the first number entered and hence the first number entered will automatically become the new max.
Likewise for min. Set it initially to Integer.MAX_VALUE. Then the first number entered will always be lower and hence become the new min.
Below code demonstrates.

import java.util.Scanner;

public class Exercicio4 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        int n;
        for (int i = 0; i < 10; i++) {
            System.out.printf("%2d. Digite um número: ", (i + 1));
            n = scan.nextInt();
            if (n > max)
                max = n;
            if (n < min)
                min = n;
        }
        System.out.println("O maior número é: " + max);
        System.out.println("O menor número é: " + min);
        scan.close();
    }
}
Related