一.Scanner
1.概念
- 一个可以使用正则表达式来解析基本类型和字符串的简单文本扫描器(最实用的地方表现在获取控制台输入)。
- 通过字符串(Readable)、输入流、文件等等来直接构建Scanner对象有了Scanner了,就可以逐段(根据正则分隔式)来扫描整个文本,并对扫描后的结果做想要的处理。
2.常用构造方法
- Scanner(InputStream source)
构造一个新的 Scanner,它生成的值是从指定的输入流扫描的。 - Scanner(File source)
- Scanner(String source)
3.Scanner默认使用空格作为分割符来分隔文本,但允许你指定新的分隔符
public class tEMP2 {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner("sds,45dfd,4f");
s.useDelimiter(",");//指定新的分隔符
System.out.println(s.delimiter());//输出此 Scanner 当前正在用于匹配分隔符的 Pattern。
while (s.hasNext()) {
System.out.println(s.next());
}
}
}
/*
* ,
* sds
* 45dfd
* 4f
*/
4.常用类
delimiter()
返回此 Scanner 当前正在用于匹配分隔符的 Pattern。
hasNext()
判断扫描器中当前扫描位置后是否还存在下一段。
hasNextLine()
如果在此扫描器的输入中存在另一行,则返回 true。
next()
查找并返回来自此扫描器的下一个完整标记。
nextLine()
此扫描器执行当前行,并返回跳过的输入信息。
5.扫描文件,并逐行输出
public class Temp2 {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner("sds,45dfd,4f");
s.useDelimiter(",");
System.out.println(s.delimiter());
while (s.hasNext()) {
System.out.println(s.next());
}
}
}
6.nextLine方法失效的问题
- 如果说获取下一行和其他获取方式一起获取的时候回出问题-该问题会导致的nextLine方法失效:
- nextLine方法以分隔符作为查找的条件,如果找到了则跳过以后的内容,当我们输入10和回车的时候实际是输入了10 /r/n
- nextInt()方法获取到10,nextLine方法获取到了/r/n,然后他就不在关心后面的内容了,所以输入失效
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
String str = sc.nextLine();
System.out.println("a="+a+",srt"+str);
//当输入3后,然后就直接输出"a=3,str="
- 解决方式:
- 重新创建一个Scanner对象(不推荐)
- sc = new Scanner(System.in);
- 推荐所有的接收都使用字符串来接收
- String a = sc.nextLine();
- String str = sc.nextLine();
- 注意会产生一个小问题:输入的类型和需要的类型不匹配(解决办法-类型转换)
- 可以再nextInt()方法后面多加一句nextLine()方法专门用来取出缓冲区中留下的空白符
- 重新创建一个Scanner对象(不推荐)
int a = sc.nextInt();
sc.nextLine();
String str = sc.nextLine();