Java: Compare two numbers
Compare Two Numbers
Write a Java program to compare two numbers.
Test Data:
Input first integer: 25
Input second integer: 39
Pictorial Presentation:
Sample Solution:
Java Code:
Explanation:
In the exercise above –
- First, it uses the "Scanner" class to obtain input from the command window (user input).
- It declares two integer variables 'number1' and 'number2' to store the two numbers provided by the user.
- It prompts the user to input the first integer using System.out.print("Input first integer: ") and reads the input into 'number1'.
- It prompts the user to input the second integer using System.out.print("Input second integer: ") and reads the input into 'number2'.
- Next it performs a series of comparisons using if statements and prints the results using System.out.printf():
- if (number1 == number2) checks if 'number1' is equal to 'number2' and prints a message if they are equal.
- if (number1 != number2) checks if 'number1' is not equal to 'number2' and prints a message if they are not equal.
- if (number1 < number2) checks if 'number1' is less than 'number2' and prints a message if 'number1' is less than 'number2'.
- if (number1 > number2) checks if 'number1' is greater than 'number2' and prints a message if 'number1' is greater than 'number2'.
- if (number1 <= number2) checks if 'number1' is less than or equal to 'number2' and prints a message accordingly.
- if (number1 >= number2) checks if 'number1' is greater than or equal to number2 and prints a message accordingly.
Sample Output:
Input first integer: 25 Input second integer: 39 25 != 39 25 < 39 25 <= 39
Flowchart:
For more Practice: Solve these Related Problems:
- Modify the program to compare three numbers.
- Write a program that compares floating-point numbers.
- Implement a function to compare numbers without using conditional operators.
- Modify the program to check for equality within a specified tolerance.
Go to:
PREV : Check Java Installation.
NEXT :
Sum of Digits.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.