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. An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation next.
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. If the next token matches the Float regular expression defined above then the token is converted into a double value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Double.parseDouble. If the token matches the localized NaN or infinity strings, then either “Nan” or “Infinity” is passed to Double.parseDouble as appropriate.
参考Java Scanner官方文档
|