Skip to content

Latest commit

 

History

History
44 lines (30 loc) · 1.68 KB

File metadata and controls

44 lines (30 loc) · 1.68 KB

Java 程序:从标准输入读取整数值

原文: https://beginnersbook.com/2017/09/java-program-to-read-integer-value-from-the-standard-input/

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

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

我们已导入包java.util.Scanner以使用Scanner。为了读取用户提供的输入,我们首先通过传递System.in作为参数来创建Scanner的对象。然后我们使用Scanner类的nextInt()方法来读取整数。如果您不熟悉 Java 并且不熟悉 java 程序的基础知识,那么请阅读核心 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 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: 101
The number entered by user: 101