Site icon TestingDocs.com

Java program for largest of three numbers

Program Description

Write a java program to find the largest of three numbers. In the program, we will prompt the user to enter three numbers. Using the if-else-if clause ladder, we will decide the largest number out of the three numbers.  

Tools Used:

Largest of Three Numbers Program

Create a new Java class and code the program logic. The program prompts the user to enter the input. Three variables are used to store the user input. In-built Java Scanner class is used to read the user input. 

The program takes a series of decisions using the if-else-if ladder control statements. The flow of the program is controlled by these statements. 

Eclipse IDE Setup

Some steps and instructions to create a Java application on Eclipse IDE:

https://www.testingdocs.com/create-a-new-java-project-in-eclipse/

https://www.testingdocs.com/create-java-package-in-eclipse-ide/

https://www.testingdocs.com/create-a-new-java-class-in-a-project/

https://www.testingdocs.com/run-java-project-in-eclipse/

Java Code

import java.util.Scanner; 

/**************************************************
 * LargestOfThreeNumbers.java
 * @program   	: LargestOfThreeNumbers Java Program. 
 * @web        	: www.TestingDocs.com
 * @version     : 1.0
 **************************************************/

public class LargestOfThreeNumbers {
  public static void main(String[] args) {
    int a, b, c; 
    Scanner sc = new Scanner(System.in); 
    System.out.print("Please enter a :=");
    a = sc.nextInt(); 
    System.out.print("Please enter b :=");
    b = sc.nextInt(); 
    System.out.print("Please enter c :=");
    c = sc.nextInt(); 
    if(a > b && a > c) {
      System.out.println("a i.e ("+ a + ") is the largest number."); 
    } else if(b > a && b > c) { 
      System.out.println("b i.e ("+ b + ") is the largest number."); 
    } else if(c > a && c > b) { 
      System.out.println("c i.e (" + c + ") is the largest number.");
    } else {
      System.out.println("Given three numbers are not distinct");
    } 
    sc.close(); 
  } 
}

 

Screenshot

Screenshot of the program in the IDE.

Program Output

Save the program and execute the program. Test and verify the output of the program. 

Please enter a :=15
Please enter b :=6
Please enter c :=22
c i.e (22) is the largest number.

Enhancements

The program expects or assumes that the user will enter proper input. There is not exception handling in the program. We can further enhance the program to incorporate exception handling with try-catch blocks.

Java Tutorials

Java Tutorial on this website: https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/in/java/

Exit mobile version