JavaScanner
中的next()
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
【注1】这里的delimiter pattern默认是正则表达式:\p{javaWhitespace}+
,表示匹配任何空白字符,因此next()
读取的内容默认去掉前后的空白符号;
【注2】可以通过,例如sc.useDelimiter(Pattern.compile(";"));
这样来改变默认的delimiter pattern;这里sc
表示Scanner
的一个对象。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
sc.useDelimiter(Pattern.compile(";"));
System.out.println("The delimiter used is "+sc.delimiter());
System.out.println(sc.next());
}
JavaScanner
中的hasNext()
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
【注】第三句直译为不会超前越过输入数据,也就是说等待输入数据。
JavaScanner
中的nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
【注1】通过line separator分割每一行的输入;
【注2】停留在下一行的开头。
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
JavaScanner
中的hasNextLine()
Returns true if there is another line in the input of this scanner. This method may block while waiting for input. The scanner does not advance past any input.
【注】和hasNext()
明显不同的是,hasNextLine()
这里是line,用line separator分割, “In any UNIX systems, line separator will return “\n” or a positive integer; and on Windows systems it returns “\r\n” or a positive integer.”;而hasNext()
是用delimiter pattern分割,默认是若干个空格。
JavaScanner
中的nextInt()
Scans the next token of the input as an int.
If the translation is successful, the scanner advances past the input that matched.
【注】粗体的第二句话表示,读入这个int
之后,scanner
会越过这个int
,但是注意,不会越过line separator
,因此如果之后的语句是nextLine()
的话,则会读入一个line separator
,即一个换行符。所以,如果要读取下一行字符串的话,应该使用两个nextLine()
。
JavaScanner
中的nextDouble()
Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.