In: Computer Science
How to use a Java program that calls for two functions. The first function is asking the user for a two integer numbers, then display the sum of the numbers. The second method is asking the user for two floating point numbers, then display the product of the numbers. Call these methods addNumbers and multiplyNumbers respectively. Call the program AddAndMultiply
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
// AddAndMultiply.java
import java.util.Scanner;
public class AddAndMultiply {
// a global Scanner variable used to read input from keyboard
private static Scanner keyboard = new Scanner(System.in);
// method to read two integers and print their sum
public static void addNumbers() {
System.out.print("Enter two integers: ");
// reading two integers
int a = keyboard.nextInt();
int b = keyboard.nextInt();
//finding sum
int sum = a + b;
System.out.println("The sum of " + a + " and " + b + " is " + sum);
}
// method to read two floats and print their product
public static void multiplyNumbers() {
System.out.print("Enter two floating point numbers: ");
// reading two floating point values (could enter integers too)
double a = keyboard.nextDouble();
double b = keyboard.nextDouble();
//finding product
double product = a * b;
System.out.println("The product of " + a + " and " + b + " is "
+ product);
}
public static void main(String[] args) {
// reading integers, displaying sum
addNumbers();
// reading floating point numbers, displaying product
multiplyNumbers();
}
}
/*OUTPUT*/
Enter two integers: 15 17
The sum of 15 and 17 is 32
Enter two floating point numbers: 5.5 1.2
The product of 5.5 and 1.2 is 6.6