Java Online Compiler
Example: Greatest of Three Numbers using Math.max() in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Greatest of Three Numbers using Math.max() import java.util.Scanner; // Only needed for user input, Math class is built-in // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Create a Scanner object and read three numbers Scanner scanner = new Scanner(System.in); System.out.print("Enter the first number: "); int num1 = scanner.nextInt(); System.out.print("Enter the second number: "); int num2 = scanner.nextInt(); System.out.print("Enter the third number: "); int num3 = scanner.nextInt(); // Step 2: Use Math.max() to find the greatest number // First, find the max of num1 and num2 int tempMax = Math.max(num1, num2); // Then, find the max of tempMax and num3 int greatest = Math.max(tempMax, num3); // Alternatively, in a single line: // int greatest = Math.max(num1, Math.max(num2, num3)); // Step 3: Print the greatest number System.out.println("The greatest number is: " + greatest); // Step 4: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS