Greatest Of Three Numbers In Java Using Scanner Class
ADVERTISEMENTS
Introduction
Determining the largest among a set of numbers is a fundamental programming task. In Java, this often involves comparing values and making decisions. In this article, you will learn how to find the greatest of three numbers using theScanner class for input, exploring several common and efficient approaches.
Problem Statement
The challenge is to accept three distinct numerical inputs from the user and then identify which of these three numbers holds the maximum value. This is a common requirement in data processing, simple decision-making logic, and validating user inputs, where understanding numerical relationships is crucial.Example
If the user inputs10, 25, and 15, the expected output should clearly indicate that 25 is the greatest number.
Background & Knowledge Prerequisites
To understand this article, readers should be familiar with:- Java Basics: Variables, data types (especially
intordouble), and operators. - Conditional Statements:
if,else if, andelseconstructs. - Input/Output in Java: Basic understanding of how to read user input, specifically using the
Scannerclass.
Required Import:
To use the Scanner class, you need to include the import java.util.Scanner; statement at the beginning of your Java file.
Use Cases or Case Studies
Finding the greatest of numbers is applicable in various real-world scenarios:- Ranking Systems: Determining the top score among three participants in a mini-game or competition.
- Resource Allocation: Identifying the highest priority task based on numerical scores (e.g., urgency, impact, cost).
- Data Validation: Ensuring a user-entered value falls within a specific range relative to two other boundary values.
- Financial Analysis: Comparing three different investment returns to find the most profitable one.
- Statistical Analysis: Finding the maximum value in a small dataset of three points without using complex statistical libraries.
Solution Approaches
Approach 1: Using if-else if-else statements
This approach uses a series of if-else if-else conditions to compare the three numbers sequentially and determine the greatest.
- One-line summary: Compares numbers in a sequential, mutually exclusive manner to find the largest.
// GreatestOfThreeUsingIfElse
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Step 2: Prompt the user to enter three numbers
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 3: Use if-else if-else to find the greatest number
if (num1 >= num2 && num1 >= num3) {
System.out.println(num1 + " is the greatest number.");
} else if (num2 >= num1 && num2 >= num3) {
System.out.println(num2 + " is the greatest number.");
} else {
System.out.println(num3 + " is the greatest number.");
}
// Step 4: Close the scanner to prevent resource leaks
scanner.close();
}
}
- Sample Output:
Enter the first number: 10 Enter the second number: 25 Enter the third number: 15 25 is the greatest number.
- Stepwise Explanation:
- A
Scannerobject is created to read input from the console. - The program prompts the user to enter three integers, which are stored in
num1,num2, andnum3. - The first
ifcondition checks ifnum1is greater than or equal to bothnum2andnum3. If true,num1is the greatest. - If the first condition is false, the
else ifcondition checks ifnum2is greater than or equal to bothnum1andnum3. If true,num2is the greatest. - If neither of the above conditions is met, it implies that
num3must be the greatest, and the finalelseblock handles this case. - The
Scannerobject is closed.
Approach 2: Using Nested if-else statements
This method involves nesting if-else conditions to compare numbers in a hierarchical manner.
- One-line summary: Determines the greatest number by comparing pairs of numbers within nested conditional blocks.
// GreatestOfThreeUsingNestedIfElse
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Create a Scanner object
Scanner scanner = new Scanner(System.in);
// Step 2: Get three numbers from the user
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 3: Use nested if-else to find the greatest number
if (num1 >= num2) {
if (num1 >= num3) {
System.out.println(num1 + " is the greatest number.");
} else {
System.out.println(num3 + " is the greatest number.");
}
} else { // num2 > num1
if (num2 >= num3) {
System.out.println(num2 + " is the greatest number.");
} else {
System.out.println(num3 + " is the greatest number.");
}
}
// Step 4: Close the scanner
scanner.close();
}
}
- Sample Output:
Enter the first number: 40 Enter the second number: 12 Enter the third number: 30 40 is the greatest number.
- Stepwise Explanation:
- Input is taken similarly to Approach 1.
- The outer
ifstatement comparesnum1andnum2.
- If
num1 >= num2, it meansnum1is potentially the greatest. The innerifthen comparesnum1withnum3. - If
num1 >= num3, thennum1is the greatest. - Otherwise (
num3 > num1),num3is the greatest. - If
num1 < num2(handled by the outerelse), it meansnum2is potentially the greatest. The innerifthen comparesnum2withnum3. - If
num2 >= num3, thennum2is the greatest. - Otherwise (
num3 > num2),num3is the greatest.
- The
Scannerobject is closed.
Approach 3: Using the Ternary Operator
The ternary operator (? :) provides a concise way to write simple if-else conditions, making the code more compact.
- One-line summary: Uses a compact conditional expression to determine the greatest value in a single line.
// GreatestOfThreeUsingTernaryOperator
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Create a Scanner object
Scanner scanner = new Scanner(System.in);
// Step 2: Get three numbers from the user
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 3: Use the ternary operator to find the greatest number
int greatest = (num1 >= num2 && num1 >= num3) ? num1 :
(num2 >= num1 && num2 >= num3) ? num2 :
num3;
// Step 4: Print the result
System.out.println(greatest + " is the greatest number.");
// Step 5: Close the scanner
scanner.close();
}
}
- Sample Output:
Enter the first number: 7 Enter the second number: 7 Enter the third number: 5 7 is the greatest number.
- Stepwise Explanation:
- Input is taken as before.
- The ternary operator evaluates conditions.
-
num1 >= num2 && num1 >= num3is checked first. If true,num1is assigned togreatest. - If false, the next condition
num2 >= num1 && num2 >= num3is checked. If true,num2is assigned togreatest. - If both are false,
num3is assigned togreatest.
- The result is printed, and the
Scanneris closed.
Approach 4: Using Math.max() method
Java's Math class provides a max() method that can find the greater of two numbers. This method can be chained to find the maximum among multiple numbers.
- One-line summary: Utilizes the built-in
Math.max()method to efficiently determine the greatest number through successive comparisons.
// GreatestOfThreeUsingMathMax
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Create a Scanner object
Scanner scanner = new Scanner(System.in);
// Step 2: Get three numbers from the user
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 3: Use Math.max() to find the greatest number
int greatest = Math.max(num1, Math.max(num2, num3));
// Step 4: Print the result
System.out.println(greatest + " is the greatest number.");
// Step 5: Close the scanner
scanner.close();
}
}
- Sample Output:
Enter the first number: 100 Enter the second number: 50 Enter the third number: 120 120 is the greatest number.
- Stepwise Explanation:
- Input is taken as before.
Math.max(num2, num3)is executed first, finding the greater ofnum2andnum3.- The result of that comparison is then used in
Math.max(num1, result_of_previous_max), effectively comparingnum1with the greater ofnum2andnum3. - The final greatest number is stored in the
greatestvariable. - The result is printed, and the
Scanneris closed.
Conclusion
This article explored various methods to find the greatest of three numbers in Java using theScanner class for input. From explicit if-else if-else and nested if-else structures to the more concise ternary operator and the efficient Math.max() method, each approach offers a valid solution with varying levels of readability and conciseness. The choice of method often depends on code readability preferences and specific project requirements.
Summary
-
if-else if-else: Straightforward, good for multiple distinct conditions. - Nested
if-else: Hierarchical comparisons, can be less readable for many conditions. - Ternary Operator: Concise for simple conditional assignments, can become complex with many conditions.
-
Math.max(): Most concise and often preferred for finding the maximum among a small set of numbers due to its simplicity and built-in efficiency. - All methods effectively use the
Scannerclass to read user input, making them interactive. - Always remember to close the
Scannerobject to prevent resource leaks.