源定义代码
final 修饰:
public final class Scanner implements Iterator<String>, Closeable { }
用法
next()读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。
nextLine()方法的结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。
一些前提知识:
import java.util.Scanner;
NoSuchElementException(父 RuntimeException)
IllegalStateException(父 RuntimeException)
InputMismatchException(父 NoSuchElementException)
1、public Scanner(InputStream source){ },用给定的输入流创建一个Scanner对象。
例1:
Scanner in = new Scanner(System.in);
例2:
InputStream in = new FileInputStream(new File("D:\\test.java"));
Scanner s = new Scanner(in);
2、public String nextLine(){ },读取输入的下一行内容。(以回车作为分隔符)。
@throws NoSuchElementException if no line was found
@throws IllegalStateException if this scanner is closed
例1:
Scanner in = new Scanner(System.in);
String name = in.nextLine();
System.out.println(name);
3、public String next(){ },读取输入的下一个单词。(以空格、回车作为分隔符)。
@throws NoSuchElementException if no more tokens are available
@throws IllegalStateException if this scanner is closed
例1:
Scanner in = new Scanner(System.in);
String name = in.next();
System.out.println(name);
4、public int nextInt(){ },读取输入的下一个int类型数据。
@throws InputMismatchException,下一个数据不是int类型或是超出int类型数据范围
@throws NoSuchElementException if input is exhausted,下一个int数据不存在
@throws IllegalStateException if this scanner is closed
public static void main(String[] args) throws FileNotFoundException {
InputStream input = new FileInputStream(new File("D:\\45\\test.txt"));
Scanner in = new Scanner(input);
for(int i=0;i<4;i++) {
int old = in.nextInt();
System.out.println(old);
}
//文件内容为:1 2 3
//抛出异常
5、public boolean hasNext(){ },判断扫描器中当前扫描位置后是否还存在下一段。(以空格、回车作为分隔符)。
@throws IllegalStateException if this scanner is closed
InputStream input = new FileInputStream(new File("D:\\45\\test.txt"));
Scanner in = new Scanner(input);
while(in.hasNext()){
System.out.println(in.next());
}
6、public boolean hasNextLine(){ }, 判断扫描器的输入中是否存在下一行。(回车作为分隔符)。
@throws IllegalStateException if this scanner is closed
InputStream input = new FileInputStream(new File("D:\\45\\test.txt"));
Scanner in = new Scanner(input);
while(in.hasNextLine()){
System.out.println(in.nextLine());
}
7、指定定界符
public Scanner useDelimiter(String pattern){}
public Scanner useDelimiter(Pattern pattern){}
8、返回作为定界符使用的 Pattern 对象
public Pattern delimiter(){}