Java中Scanner类广泛用于读取输入。
Scanner scan = new Scanner(System.in);
通过System.in stream创建了一个新的Scanner对象
scan.next(); // returns the next token of input
scan.hasNext(); // returns true if there is another token of input
(false otherwise)
scan.nextLine() // returns the next LINE of input
scan.hasNextLine(); // returns true if there is another line of input
关闭输入流:
scan.close();
Scanner也针对不同的数据类型有不同的readNext和hasNext方法,当你准确知晓读入类型时很有帮助。
那么下面重点来了:
next系列方法读取的是tokens(你也可以当作word),而nextLine系列的方法从Scanner当前的位置读至下一行的开始。
多行输入的每一行都包含一个不可见的分隔符用以表示已到达该行输入的末端。当使用Scanner中的方法读取tokens (例如: next(), nextInt()等), Scanner读取并返回下一个token. 当你读取一整行 (例如: readLine()),将从当前位置读至下一行的开始。正因为如此,如果在上一次读取的末尾到下一行的开头之间没有字符, 调用 nextLine() 方法可能会返回一个空字符串。
例如,给定以下输入:
a b c
d e
f
g
以下分解顺序调用Scanner类中的不同read方法:
1.调用scan.next(); 返回a
2.调用scan.next(); 返回下一个符号 b.
3.调用scan.nextLine(); 返回下一个符号 c.
注意:返回一个空格和一个字母,因为从上一个符号的末端读到下一行的开始。
4.继续调用scan.nextLine(); 返回下一行内容 d e.
5.调用scan.next(); 返回下一符号 f.
6.调用scan.nextLine(); 返回 f 之后到下一行开头的所有东西,因为这之间没有字符,所以返回了空字符串。
7.调用scan.nextLine(); 返回 g.
Note: You must understand what happens when you switch between reading a token (single word) of input and reading an entire line of input.
重点是要理解在读取单个字符和读取整行之间转换时会发生什么。