Here we will see two Java programs, the first program takes two integer numbers (entered by the user) and displays the product of these numbers. The second program takes any two numbers (may be integers or floating points) and displays the result.
Program to read two integer and print product of them
This program asks the user to enter two integer numbers and display the product. To understand how to use a scanner to take user input, checkout this program: program to read integers from system input.
import java.util.Scanner; public class Demo { public static void main(String[] args) { /* This reads the input provided by user * using keyboard */ Scanner scan = new Scanner(System.in); System.out.print("Enter first number: "); // This method reads the number provided using keyboard int num1 = scan.nextInt(); System.out.print("Enter second number: "); int num2 = scan.nextInt(); // Closing Scanner after the use scan.close(); // Calculating product of two numbers int product = num1*num2; // Displaying the multiplication result System.out.println("Output: "+product); } }
Output:
Enter first number: 15 Enter second number: 6 Output: 90
Read two integer or floating point numbers and display the multiplication
Here we are using data type double for numbers so that you can enter integers as well as floating point numbers.
import java.util.Scanner; public class Demo { public static void main(String[] args) { /* This reads the input provided by user * using keyboard */ Scanner scan = new Scanner(System.in); System.out.print("Enter first number: "); // This method reads the number provided using keyboard double num1 = scan.nextDouble(); System.out.print("Enter second number: "); double num2 = scan.nextDouble(); // Closing Scanner after the use scan.close(); // Calculating product of two numbers double product = num1*num2; // Displaying the multiplication result System.out.println("Output: "+product); } }
Output:
Enter first number: 1.5 Enter second number: 2.5 Output: 3.75