I can’t find the smallest number

Asked

Viewed 358 times

-5

Good afternoon

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

So far I’ve only been able to find the biggest 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);
}

}

  • 2

    Would that be Greater and lesser number ?

  • Not for example

  • type 3 numbers 3,1,2 in the final result appears The largest and 3 the smallest and 2

  • 1

    if (nums >= bigger) { smaller = bigger; bigger = nums; } Else { smaller = nums; ;}

  • This is not working

1 answer

1

The easiest way to do this is to add your numbers to an Integers array 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);
}
  • 1

    Thank you Dot Net

  • These are things that are always learning, I’ve been without programming for some time and I’ve resumed now and I’m having some difficulty starting over

  • It’s working perfectly Bound

Browser other questions tagged

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