Java 实例 从标准输入读取整数值

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

在这个程序中,我们将看到如何读取用户输入的整数。Scanner类位于java.util包中。它用于捕获原始类型的输入,如int,double等和字符串。

示例:用于读取用户输入的数字的程序

我们已导入包java.util.Scanner以使用Scanner。为了读取用户提供的输入,我们首先通过传递System.in作为参数来创建Scanner的对象。然后我们使用Scanner类的nextInt()方法来读取整数。

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 any number: ");        // This method reads the number provided using keyboard        int num = scan.nextInt();        // Closing Scanner after the use        scan.close();        // Displaying the number         System.out.println("The number entered by user: "+num);    }}

输出:

Enter any number: 101The number entered by user: 101

相关推荐