Peter Parker Peter Parker - 3 months ago 12
Java Question

Finding the smallest, largest, and middle values in Java

I did with this code. Is it correct way? I want to sort the numbers in ascending order. Is there better way for this?

import java.lang.Math;
public class Numbers
{
public static void main(String[] args)
{
int a=1;
int b=2;
int c=3;

if (a<b && a<c)
System.out.println("Smallest: a");
else if (a>b && a>c)
System.out.println("Biggest: a");
else if (a>b && a<c)
System.out.println("Mid: a");
else if (a<b && a>c)
System.out.println("Mid: a");
if (b<c && b<a)
System.out.println("Smallest: b");
else if (b>c && b>a)
System.out.println("Biggest: b");
else if (b>c && b<a)
System.out.println("Mid: b");
else if (b<c && b>a)
System.out.println("Mid: b");
if (c<a && c<b)
System.out.println("Smallest: c");
else if (c>a && c>b)
System.out.println("Biggest: c");
else if (c>a && c<b)
System.out.println("Mid: c");
else if (c<a && c>b)
System.out.println("Mid: c");
}
}

Answer

Expanding on Steve's answer (I assume you are new to Java and need a more complete example):

import java.util.Arrays;

public class Numbers
{
  public static void main(String[] args)
  {
    int a=3;
    int b=2;
    int c=1;
    int[] numbers = {a,b,c};
    Arrays.sort(numbers);
    System.out.println("The highest number is "+numbers[2]);
    System.out.println("The middle number is "+numbers[1]);
    System.out.println("The lowest number is "+numbers[0]);
  }
}
Comments