Task #5: Writing value returning Method
In this task, you are being asked to write value returning method in Java.
Your job is to write a program which will take two integer numbers as input and returns:
0, if both numbers are equal.
1, if first number is greater than second number.
-1, if first number is less than second number.
You may use the following header for this method:
static int compare(int firstNumber, int secondNumber)
Take input from the user, call the method and print the appropriate messages according to the
result.
1. Create a program called CompareNumberLab1.java.
2. Create appropriate variables and assign values using a Scanner object.
3. Correctly display appropriate messages.s
import java.util.InputMismatchException;
import java.util.Scanner;
public class CompareNumberLab1 {
private static int compare(int firstNumber, int secondNumber) {
if (firstNumber > secondNumber) {
return 1;
} else if (firstNumber < secondNumber) {
return -1;
} else {
return 0;
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int firstNumber, secondNumber;
System.out.println("Enter first number:");
while (true) {
try {
firstNumber = input.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("The entered number is incorrect, please try again...");
input.next();
}
}
System.out.println("Enter second number:");
while (true) {
try {
secondNumber = input.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("The entered number is incorrect, please try again...");
input.next();
}
}
int comparison = compare(firstNumber, secondNumber);
switch (comparison) {
case 0:
System.out.println("Both numbers are equal!");
break;
case -1:
System.out.println("First number is less than second number!");
break;
case 1:
System.out.println("First number is greater than second number!");
break;
}
}
}
Comments
Leave a comment