Java 实例 相乘两个数字

来源:这里教程网 时间:2026-02-17 20:16:14 作者:

当您开始学习java 编程时,您在作业中遇到了这些类型的问题。这里我们将看到两个 Java 程序,第一个程序接受两个整数(由用户输入)并显示这些数字的乘积。第二个程序采用任意两个数字(可以是整数或浮点数)并显示结果。

示例 1:读取两个整数并打印它们的产品

该程序要求用户输入两个整数并显示产品。要了解如何使用扫描仪获取用户输入,请检查此程序:程序从系统输入读取整数。

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("输出: "+product);    }}

输出:

Enter first number: 15Enter second number: 6输出: 90

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

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

这里我们使用数据类型double 作为数字,这样你就可以输入整数和浮点数。

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("输出: "+product);    }}

输出:

Enter first number: 1.5Enter second number: 2.5输出: 3.75

相关推荐