How to return the second lowest value in java?

1

How to return the second lowest value given a string (of indefinite size) of numbers in java? I have the code that returns the smallest value, which looks like this:

import java.util.Scanner;

public class SegundoMenor {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.print(menor(input));
    }

    public static int menor(Scanner input) {
        int menor = Integer.MAX_VALUE;
        while(input.hasNextInt()) {
            int x = input.nextInt();
            if (x < menor) {
                menor = x;
            }
        }
        return menor;
    }
}

I would like to get the second lowest value.

    
asked by anonymous 11.05.2018 / 19:22

1 answer

1

You can do this:

import java.util.Scanner;

public class SegundoMenor {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.print(segundoMenor(input));
    }

    public static int segundoMenor(Scanner input) {
        int menor = Integer.MAX_VALUE;
        int segundoMenor = Integer.MAX_VALUE;
        while (input.hasNextInt()) {
            int x = input.nextInt();
            if (x < menor) {
                segundoMenor = menor;
                menor = x;
            } else if (x < segundoMenor) {
                segundoMenor = x;
            }
        }
        return segundoMenor;
    }
}
    
11.05.2018 / 22:35