Home  >  Article  >  Java  >  How to use keyboard input in java

How to use keyboard input in java

(*-*)浩
(*-*)浩Original
2019-11-11 10:52:235240browse

When the program needs to obtain the commands or data entered by the user from the keyboard, for example: obtain the calculation expression entered by the user. User input can be easily obtained through the Scanner class.

How to use keyboard input in java

When obtaining user input through the Scanner class, the console will wait for the user's input until the user hits the Enter key to complete the input. The content is passed to the Scanner. If the program wants to obtain the input content from the Scanner, it only needs to call the Scanner's nextLine() method. (Recommended learning: java course)

Initialization of the Scanner class

Declare a scanner variable and instantiate the Scanner using the new operator , when instantiating Scanner, you need to pass in the System.in object. Scanner obtains user input through the passed in System.in and processes the characters entered by the user, shielding the complex operation of obtaining user input.

Scanner scanner = new Scanner(System.in);

Next we demonstrate the simplest data input and obtain the input string through the next() and nextLine() methods of the Scanner class. Before reading, we generally need to use hasNext and hasNextLine Determine whether there is still input data:

Use next method:

ScannerDemo.java file code:

import java.util.Scanner; 
 
public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 从键盘接收数据
        // next方式接收字符串
        System.out.println("next方式接收:");
        // 判断是否还有输入
        if (scan.hasNext()) {
            String str1 = scan.next();
            System.out.println("输入的数据为:" + str1);
        }
        scan.close();
    }
}

The output result of executing the above program is:

$ javac ScannerDemo.java
$ java ScannerDemo
next方式接收:
runoob com
输入的数据为:runoob

The above is the detailed content of How to use keyboard input in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn