Java Online Compiler
Example: Greatest of Three using Nested Ternary Operator in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Greatest of Three using Nested Ternary Operator import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Initialize Scanner for user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt user to enter three numbers System.out.print("Enter first number: "); int num1 = scanner.nextInt(); System.out.print("Enter second number: "); int num2 = scanner.nextInt(); System.out.print("Enter third number: "); int num3 = scanner.nextInt(); // Step 3: Use nested ternary operator to find the greatest number // (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3); // Explanation: // If num1 > num2 is true: // Then compare num1 with num3. The greater of these two is the result. // If num1 > num2 is false (meaning num2 >= num1): // Then compare num2 with num3. The greater of these two is the result. int greatest = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3); // Step 4: Display the greatest number System.out.println("The greatest number is: " + greatest); // Step 5: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS