Scanner类
创建Scanner对象
- 从键盘读取
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
- 从字符串读取
Scanner sc = new Scanner("Hello World 123");
- 从文件读取
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
try {
Scanner sc = new Scanner(new File("data.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
常用方法分类
判断是否有下一个输入
- hasNext()
- hasNextInt()
- hasNextDouble()
- hasNextLine()
读取输入
- next() 读取下一个token
- nextInt() 读取下一个整数
- nextDouble() 读取下一个浮点数
- nextLine()
- nextBoolean()
- nextLong()
- nextshort()
- nextByte()
- nextFloat()