Larger and smaller number

4

I need to sort three numbers and I can not use for or vectors.

I know it's easy but I can not do it. My problem is: I can not save the highest value.

     public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int menor = 0;
    int maior = 0;
    System.out.println(" Tres números:");
    int a = sc.nextInt();
    int b = sc.nextInt();
    int c = sc.nextInt();



    if((a < b) && (a < c))
        menor = a;

    else if((b < a)&&(b < c))
        menor = b;

    else if((c < a)&&(c < b))
        menor = c;

    System.out.println(" Maior: " + maior + " Menor:" + menor);
}

Oops, I think I got it resolved.

if((a < b) && (a < c))
        menor = a;

    else if((b < a)&&(b < c))
        menor = b;

    else if((c < a)&&(c < b))
        menor = c;

    if((a > b) && (a > c))
        maior = a;

    else if((b > a)&&(b > c))
        maior = b;

    else if((c > a)&&(c > b))
        maior = c;
    System.out.println(" Maior: " + maior + " Menor:" + menor);
}
    
asked by anonymous 29.01.2016 / 17:31

2 answers

4

A simple way would be this:

import java.util.Scanner;

class Ideone {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println(" Tres números:");
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        int menor = a;
        int maior = a;

        if (b > maior) {
            maior = b;
        }
        if (c > maior) {
            maior = c;
        }
        if (b < menor) {
            menor = b;
        }
        if (c < menor) {
            menor = c;
        }
        System.out.println(" Maior: " + maior + " Menor: " + menor);
    }
}

See running on ideone .

Obviously there are other ways to do this, but this is simple.

    
29.01.2016 / 17:45
2

Another option would be this:

import java.util.Scanner;

class Ideone {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println(" Tres números:");
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        int menor;
        int maior;

        maior = Math.max(b,Math.max(c,a));
        menor = Math.min(b,Math.min(c,a));

        System.out.println(" Maior: " + maior + " Menor: " + menor);
    }
}

The expression below uses the Math.max function to get the highest value between two values. First, it compares c with a . Shortly thereafter, the result is compared with b . In the end, the greater of those three will be returned.

Math.max(b,Math.max(c,a))

The same holds true for the smaller one, however, using the Math.min function.

    
29.01.2016 / 17:59