1. Introduction
Finding the largest of three numbers is a basic programming exercise that helps beginners understand conditional statements and user input in Java. By comparing three numbers inputted by the user, we can determine which one is the largest.
2. Program Steps
1. Import the Scanner class from the java.util package for user input.
2. Define the main class named LargestOfThree.
3. Inside the main class, define the main method.
4. Inside the main method, create an object of the Scanner class to take user input.
5. Prompt the user to enter three numbers and store them in variables.
6. Compare the three numbers using conditional statements to find the largest one.
7. Print the largest number to the console.
3. Code Program
import java.util.Scanner; // 1. Importing Scanner class for user input
public class LargestOfThree { // 2. Defining the main class
public static void main(String[] args) { // 3. Defining the main method
Scanner input = new Scanner(System.in); // 4. Creating Scanner object to take user input
System.out.print("Enter first number: "); // 5. Prompting user for the first number
double num1 = input.nextDouble(); // Storing the first number in variable num1
System.out.print("Enter second number: "); // Prompting user for the second number
double num2 = input.nextDouble(); // Storing the second number in variable num2
System.out.print("Enter third number: "); // Prompting user for the third number
double num3 = input.nextDouble(); // Storing the third number in variable num3
double largest; // Defining variable to store the largest number
// 6. Comparing the three numbers to find the largest one
if (num1 >= num2 && num1 >= num3) {
largest = num1;
} else if (num2 >= num1 && num2 >= num3) {
largest = num2;
} else {
largest = num3;
}
System.out.println("The largest number is: " + largest); // 7. Printing the largest number
input.close(); // Closing the Scanner object to avoid memory leak
}
}
Output:
Enter first number: 25 Enter second number: 48 Enter third number: 37 The largest number is: 48.0
4. Step By Step Explanation
– Step 1: The Scanner class from the java.util package is imported, enabling the program to receive user input.
– Step 2: The main class named LargestOfThree is defined.
– Step 3: The main method is defined inside the main class, acting as the entry point for the program.
– Step 4: A Scanner object named "input" is created to receive user input.
– Step 5: The user is prompted to input three numbers, 25, 48, and 37, which are stored in variables num1, num2, and num3 respectively.
– Step 6: Using conditional if-else statements, the three numbers are compared, and the largest number, 48, is identified and stored in the variable largest.
– Step 7: The program then prints out the largest number, 48, to the console.
– Lastly, the Scanner object is closed to prevent any potential memory leak.