Scanner类
Scanner 属于 java.util 包,常用于从键盘、文件或字符串中读取数据。
键盘输入
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = sc.next();
int age = sc.nextInt();
System.out.println(name + age);
sc.close();
}
}常用方法
| 方法 | 作用 |
|---|---|
next() | 读取一个单词,遇到空白结束 |
nextLine() | 读取一整行 |
nextInt() | 读取 int |
nextDouble() | 读取 double |
hasNext() | 判断是否还有输入 |
hasNextInt() | 判断下一个输入能否作为 int |
next() 和 nextLine()
next():只读到空格前。nextLine():读完整一行,包括空格。
常见坑:先用 nextInt(),再用 nextLine() 时,nextLine() 可能读到上一行残留的换行符。
int age = sc.nextInt();
sc.nextLine(); // 吃掉换行符
String name = sc.nextLine();从字符串中读取
Scanner sc = new Scanner("10 20 30");
while (sc.hasNextInt()) {
System.out.println(sc.nextInt());
}使用建议
- 简单控制台输入用
Scanner。 - 大量数据输入时,
Scanner较慢,可改用BufferedReader。 - 用完可以
close(),但关闭System.in后后续不能再从控制台读取。