Java if statement sort three integers

Question

We would like to write a program that prompts the user to enter three integers and display the integers in non-decreasing order.

public class Main {
  public static void main(String[] args) {
    java.util.Scanner input = new java.util.Scanner(System.in);

    // Enter three numbers
    System.out.print("Enter three integers: ");
    int number1 = input.nextInt();
    int number2 = input.nextInt();
    int number3 = input.nextInt();

    //your code here

    System.out.println("The sorted numbers are "
      + number1 + " " + number2 + " " + number3);
  }/*w w  w . j a va2 s.  co m*/
}



public class Main {
  public static void main(String[] args) {
    java.util.Scanner input = new java.util.Scanner(System.in);

    // Enter three numbers
    System.out.print("Enter three integers: ");
    int number1 = input.nextInt();
    int number2 = input.nextInt();
    int number3 = input.nextInt();

    if (number1 > number2) {
      int temp = number1;
      number1 = number2;
      number2 = temp;
    }

    if (number2 > number3) {
      int temp = number2;
      number2 = number3;
      number3 = temp;
    }

    if (number1 > number2) {
      int temp = number1;
      number1 = number2;
      number2 = temp;
    }

    System.out.println("The sorted numbers are "
      + number1 + " " + number2 + " " + number3);
  }
}

The following code uses Arrays class to do the sorting.

import java.util.Scanner;
import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter three integers: ");
    int a = input.nextInt();
    int b = input.nextInt();
    int c = input.nextInt();

    int[] sorted = sortThree(a, b, c);

    for (int num: sorted) {
      System.out.printf("%d ", num);
    }//  w w  w. ja  v a  2 s  .  com
    System.out.println();
  }

  private static int[] sortThree(int a, int b, int c) {
    int[] nums = new int[]{a, b, c};
    Arrays.sort(nums);
    return nums;
  }
}



PreviousNext

Related