In: Computer Science
IN JAVA
Write a MAIN METHOD that asks for user input of a positive integer and a negative integer validates the inputs using a loop and then calls the METHOD from Question 3 and prints the result. The MAIN should have two variables (appropriately typed), get the input from the user and store them in the variables after validating them, then call the method from question 3 (sending parameters, if necessary) and print the returned value with an appropriate descriptive statement.
// Question 3
/*
public static int sum(int num1, int num2){
int both;
both = num1 + num2;
return both;
}
*/
Below is your code:
import java.util.Scanner;
public class Numbers {
// main method
public static void main(String[] args) {
// declaring two variables
int positiveNumber = -1;
int negativeNumber = 0;
// declaring Scanner to get user input
Scanner keyboard = new Scanner(System.in);
// getting input for first variable
while (positiveNumber < 0) {
// prompt user to input a positive number
System.out.print("Enter a positive number: ");
// getting input from user
positiveNumber = keyboard.nextInt();
// if number entered is negative, print error and get input again
if (positiveNumber < 0) {
System.out.println("Please enter a valid number.");
}
}
// getting input for second variable
while (negativeNumber >= 0) {
// prompt user to input a negative number
System.out.print("Enter a negative number: ");
// getting input from user
negativeNumber = keyboard.nextInt();
// if number entered is positive or 0, print error and get input
// again
if (negativeNumber >= 0) {
System.out.println("Please enter a valid number.");
}
}
// calling method to get sum
int sum = sum(positiveNumber, negativeNumber);
// printing result
System.out.println("Sum of two numbers i.e. " + positiveNumber
+ " and " + negativeNumber + " is: " + sum);
// closing scanner
keyboard.close();
}
// method from Question 3
public static int sum(int num1, int num2) {
int both;
both = num1 + num2;
return both;
}
}
Output
Enter a positive number: -8
Please enter a valid number.
Enter a positive number: -6
Please enter a valid number.
Enter a positive number: 8
Enter a negative number: 6
Please enter a valid number.
Enter a negative number: 7
Please enter a valid number.
Enter a negative number: -4
Sum of two numbers i.e. 8 and -4 is: 4