最近在刷题时,输入输出遇到了很大的困扰,被Scanner类弄糊涂了,故将其整理出来。
Scanner类
java.util.Scanner 是 Java5 的新特征。其中关于Scanner类的描述如下:
A simple text scanner which can parse primitive types and strings using regular expressions.
大意就是“一个可以使用正则表达式来解析基本类型和字符串的简单文本扫描器”,其主要功能是简单本文本扫描器。这个类最实用的地方就是获取控制台的输入。
Scanner的构造方法
关于Scanner的构造方法有很多,可以用字符串,输入流,文件等来直接构造Scanner对象。
举个例子
public class Main {
public static void main(String[] args) throws Exception{
//第一种方式:用文件流
File file = new File("C:\\Users\\Administrator\\Desktop\\note.txt");
Scanner s1 = new Scanner(file);
//第二方式:用字符串初始化
String str = "fjdi kjfdsj fjdskl";
Scanner s2 = new Scanner(str);
//第三方是:用标准输入初始化,获取控制台的输入
Scanner s3 = new Scanner(System.in);
}
}
Scanner的方法函数
从Java的api中可以看到Scanner类有许多的方法函数,我们今天将几个常用的函数:
- void close() :关闭此扫描器。
- Pattern delimiter() :返回此 Scanner 当前正在用于匹配分隔符的 Pattern。
- boolean hasNext() :如果此扫描器的输入中有另一个标记,则返回 true。
- String next() : 查找并返回来自此扫描器的下一个完整标记。
- int nextInt() : 将输入信息的下一个标记扫描为一个 int。(类似的还有nextByte(),nextDouble(),nextFloat()等)
- String nextLine() :此扫描器执行当前行,并返回跳过的输入信息。
- hasNextLine() : 如果在此扫描器的输入中存在另一行,则返回 true。
掌握了以上5个方法就大致掌握了Scanner的使用方法。举个例子:
import java.io.File;
import java.util.Scanner;
public class Note_Scanner {
//获取控制台的输入
public static void Demo(){
Scanner in = new Scanner(System.in);
System.out.println("请输入:");
while(in.hasNext()){
String str = in.next();
System.out.println(str);
}
in.close();
}
//Scanner使用指定分割符来分隔字符串
public static void Demo_1(){
String str = "hello word!";
Scanner s = new Scanner(str);
s.useDelimiter(" "); //使用“ ”空格作为分割符
while(s.hasNext()){
System.out.println(s.next());
}
s.close();
}
public static void main(String[] args) {
Demo();
//Demo_1();
}
}
next()、nextInt()与nextLine()三者的区别
next()
- next() 方法遇见第一个有效字符(非空格,非换行符)时,开始扫描。
- 当遇见第一个分隔符或结束符(空格或换行符)时,结束扫描。
- 获取扫描到的内容,即获得第一个扫描到的不含空格、换行符的单个字符串。
nextInt()
- nextInt()只读取数值。
- 遇到空格符、换行符就结束扫描
- 当扫描的不是Int型数值就会报错
nextLine()
- 以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
- 可以获得空白。
举个例子
import java.io.File;
import java.util.Scanner;
public class Note_Scanner {
//nextInt()
public static void nextIntDemo(){
Scanner in = new Scanner(System.in);
System.out.println("请输入数字:"); //输入:“123 456 78”试试看
while(in.hasNext()){
int t = in.nextInt();
System.out.println(t);
}
in.close();
}
//next()
public static void nextDemo(){
Scanner in = new Scanner(System.in);
System.out.println("请输入字符串:"); //输入:“hello world!”试试看
while(in.hasNext()){
String str = in.next();
System.out.println(str);
}
in.close();
}
//nextLine()
public static void nextLineDemo(){
Scanner in = new Scanner(System.in);
System.out.println("请输入字符串:"); //输入: 多输入几行试试看
while(in.hasNextLine()){
String str = in.nextLine();
System.out.println(str);
}
in.close();
}
public static void main(String[] args) {
nextIntDemo();
//nextDemo();
//nextLineDemo();
}
}