Java Program to Find Largest Between Three Numbers Using Ternary Operator
In this program ternary operator (?, >, : ) to find the largest number as the output is used. The below program taking three numbers from the user and checked it with the ternary operator and print the greatest among the three numbers.
import java.io.*;
import java.io.*;
public class GreatestNumberUsingTernary
{
public static void
main(String[] args)
{
Int a,b,c;
InputStreamReader in =
new InputStreamReader(System.in);
BufferedReader br = new
BufferedReader(in);
System.out.println("Enter three numbers to find greatest : ");
// Inputing three number from the user
a =
Integer.parseInt(br.readLine());
b =
Integer.parseInt(br.readLine());
c =
Integer.parseInt(br.readLine());
d = c > (a > b ? a : b) ? c : ((a > b) ? a : b);
System.out.println("Greatest
Number:"+d);
}
}
Write a program to input three numbers and find the greatest of them.
In the following, we are taking three numbers from users as input and checked the number using if..else if statement and compiled and successfully print the output. We have given a simple description of the variable too.
Solution
Solution
import java.io.*;
public class GreatestNumber
{
// main method begins
public static void main (String args[]) throws IOException
{
int number1, number2, number3;
number1 = number2 = number3 = 0;
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
System.out.println("Enter three numbers to find greatest : ");
// Waiting for the user input
number1 = Integer.parseInt(br.readLine());
number2 = Integer.parseInt(br.readLine());
number3 = Integer.parseInt(br.readLine());
// Checking number1 with number2 and number1 with number3
// if satisfied then print number1 as greatest.
// if satisfied then print number1 as greatest.
if (number1 > number2 && number1 > number3)
{
System.out.println (number1 + " is greatest");
}
// Checking number2 with number1 and number2 with number3
// if satisfied then print number3 as greatest.
// Checking number2 with number1 and number2 with number3
// if satisfied then print number3 as greatest.
else if (number2 > number1 && number2 > number3)
{
System.out.println (number2 + " is the greatest");
}
// if above condition is not satisefied the it print number3
// if above condition is not satisefied the it print number3
else
{
System.out.println (number3 + " is the greatest");
}
} // end method main
} // end class
Enter three numbers to find the greatest :
9
2
5
9 is the greatest
Enter three numbers to find the greatest :
10
30
13
30 is the greatest
SN
|
Variables/Function
|
Type
|
Description
|
1.
|
in
|
object
|
InputStreamReader object
|
2.
|
br
|
object
|
BufferedReader object
|
3.
|
number1
|
int
|
First number
|
4.
|
number2
|
int
|
Second number
|
5.
|
Number3
|
int
|
Third number
|
6.
|
main()
|
User-defined Function
|
Starting of java program
|