I can not find the smallest number

-5

Good afternoon

Given a nonnegative integer n and n nonnegative integers, indicate which of these numbers is the largest and the smallest.

So far I've only been able to find the biggest one that anyone can help My code below:

package exe10ficha1;
import javax.swing.JOptionPane;
public class Exe10ficha1 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    int num;
    int nums;
    int maior = 0;
    int menor = 0;
    int i;
    int aux;

    num = Integer.parseInt(JOptionPane.showInputDialog("Indique um valor"));

    if (num > 0) {
        for (i = 1; i <= num; i++) {
            nums = Integer.parseInt(JOptionPane.showInputDialog("Indique um valor"));

            if (nums <= 0) {
                System.out.println("O valor e invalido");
                System.exit(0);
            }

            if (nums >= maior) {
                maior = nums;
            } else {
                menor = nums;
            }
        }
    }

    System.out.println("O maior e: " + maior);
    System.out.println("O menor e: " + menor);
}

}

    
asked by anonymous 07.06.2016 / 19:04

1 answer

1

The easiest thing to do is to add your numbers to an array of Inters and then use Collections.min and Collections.max.

 if (num > 0) {
  Integer[] numbers = new Integer[num]
    for (i = 0; i <= num; i++) {
        numbers[i] = Integer.parseInt(JOptionPane.showInputDialog("Indique um valor"));

        if (numbers[i] <= 0) {
            System.out.println("O valor e invalido");
            System.exit(0);
        }
    }

    int min = (int) Collections.min(Arrays.asList(numbers));
    int max = (int) Collections.max(Arrays.asList(numbers));

    System.out.println("O menor é: " + min);
    System.out.println("O maior é: " + max);
}
    
07.06.2016 / 19:42