# Java 程序乘以两个数字

> 原文： [https://beginnersbook.com/2017/09/java-program-to-multiply-two-numbers/](https://beginnersbook.com/2017/09/java-program-to-multiply-two-numbers/)

当您开始学习 [java 编程](https://beginnersbook.com/java-tutorial-for-beginners-with-examples/)时，您在作业中遇到了这些类型的问题。这里我们将看到两个 Java 程序，第一个程序接受两个整数（由用户输入）并显示这些数字的乘积。第二个程序采用任意两个数字（可以是整数或浮点数）并显示结果。

## 示例 1：程序读取两个整数并打印它们的产品

该程序要求用户输入两个整数并显示产品。要了解如何使用扫描仪获取用户输入，请检查此程序：[程序从系统输入](https://beginnersbook.com/2017/09/java-program-to-read-integer-value-from-the-standard-input/)读取整数。

```java
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);
    }
}
```

**输出：**

```java
Enter first number: 15
Enter second number: 6
Output: 90
```

## 示例 2：读取两个整数或浮点数并显示乘法

在上面的程序中，我们只能整数。如果我们想计算两个浮点数的乘积怎么办？此程序允许您输入浮点数并计算产品。

这里我们使用[数据类型](https://beginnersbook.com/2017/08/data-types-in-java/) double 作为数字，这样你就可以输入整数和浮点数。

```java
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:**

```java
Enter first number: 1.5
Enter second number: 2.5
Output: 3.75
```