How to return the second lowest java value?

Asked

Viewed 261 times

1

How to return the second smallest value given a series (of indefinite size) of numbers in java? I have the code that returns the smallest value, which looked 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’d like to take the second lowest.

  • It would not be better to make an array and sort that array and take the second item from the list that will be the second smallest?

  • @Tiagoferezin depends. If this is an exercise to demonstrate that you know how to do the algorithm in hand, no. If the exercise is to find any solution, then it may be.

  • @Tiagoferezin good idea thank you very much!

  • /@Andradelucas Poste answers how he did to help others

1 answer

1


You can do it like 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;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.