Scanner class introduction
java.util.Scanner is a new feature of Java5. User input can be obtained through the Scanner class.
Basic syntax for creating a Scanner object:
Scanner s = new Scanner(System.in);
(Video tutorial recommendation: java video)
Example:
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 to determine whether there is still input data:
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 results are as follows:
$ javac ScannerDemo.java $ java ScannerDemo next方式接收: php cn 输入的数据为:php
Recommended tutorial:java entry program
The above is the detailed content of How to use the Scanner class in java. For more information, please follow other related articles on the PHP Chinese website!