Java Math find the largest and smallest

Question

We would like to find the largest and smallest among three integer read from console

import java.util.Scanner;

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

    System.out.print("Enter three spaced separated integers: ");
    int x = input.nextInt();
    int y = input.nextInt();
    int z = input.nextInt();
    input.close();//  w  w  w .ja  va2 s .  c  o m
    
    //your code here
  }

  // print result
  private static void printResult(String message, int x) {
    System.out.printf("%s = %d\n", message, x);
  }
}



import java.util.Scanner;

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

    System.out.print("Enter three spaced separated integers: ");
    int x = input.nextInt();
    int y = input.nextInt();
    int z = input.nextInt();
    input.close();
    
    // largest
    printResult("Largest", Math.max(x, Math.max(y, z)));

    // smallest
    printResult("Smallest", Math.min(x, Math.min(y, z)));
  }

  // print result
  private static void printResult(String message, int x) {
    System.out.printf("%s = %d\n", message, x);
  }
}



PreviousNext

Related