为什么hasNext()为False,但hasNextLine()为True? [英] Why is hasNext() False, but hasNextLine() is True?
问题描述
对于扫描仪对象, hasNextLine()
方法如何返回true code> hasNext()方法返回false?
How is it that for a scanner object the hasNextLine()
method returns true while the hasNext()
method returns false?
注意:根据输入文件, hasNext ()
方法按预期返回结果; hasNextLine()
似乎没有返回正确的结果。
Note: Based on the input file, the hasNext()
method is returning the result as expected; the hasNextLine()
does not seem to be returning the correct result.
以下是我正在运行的代码,它创建了以下结果:
Here's the code I'm running that's creating the results below:
public void ScannerTest(Reader fileReaderObject){
Scanner scannerObj = new Scanner(fileReaderObject);
for(int i = 1; scannerObj.hasNext(); i++){
System.out.println(i + ": " + scannerObj.next());
System.out.println("Has next line: " + scannerObj.hasNextLine());
System.out.println("Has next: " + scannerObj.hasNext());
}
System.out.println();
scannerObj.close();
}
输入文件
以下是我传递给此扫描仪的文件的实际内容:
Input File
The following is the actual content of the file that I'm passing to this scanner:
a 3 9
b 3 6
c 3 3
d 2 8
e 2 5
f 2 2
g 1 7
h 1 4
i 1 1
结果
以下是控制台中打印内容的结尾当我运行我的代码,并包含我无法理解的部分:
Result
The following is the end of what's printed in the console when I run my code, and includes the portion I can't make sense of:
25: i
Has next line: true
Has next: true
26: 1
Has next line: true
Has next: true
27: 1
Has next line: true
Has next: false
推荐答案
你在文件末尾有一个额外的换行符。
-
hasNextLine()
chec ks以查看缓冲区中是否还有另一个linePattern
。 -
hasNext()
检查到查看缓冲区中是否有可解析的令牌,由扫描器的分隔符分隔。 hasNextLine()
checks to see if there is anotherlinePattern
in the buffer.hasNext()
checks to see if there is a parseable token in the buffer, as separated by the scanner's delimiter.
You have a single extra newline at the end of your file.
由于扫描器的分隔符是空格,并且 linePattern
也是空格,缓冲区中可能有 linePattern
,但没有可解析的令牌。
Since the scanner's delimiter is whitespace, and the linePattern
is also white space, it is possible for there to be a linePattern
in the buffer but no parseable tokens.
通常,解析所有令牌后始终调用 nextLine()
来处理此问题的最常见方法(例如数字)在你的文字的每一行。在从 System.in
中读取用户输入时,使用扫描程序
时需要执行此操作。要使扫描程序超过此空白分隔符,必须使用 scanner.nextLine()
清除行分隔符。请参阅:使用scanner.nextLine()
Typically, the most common way to deal with this issue by always calling nextLine()
after parsing all the tokens (e.g. numbers) in each line of your text. You need to do this when using Scanner
when reading a user's input too from System.in
. To advance the scanner past this whitespace delimiter, you must use scanner.nextLine()
to clear the line delimiter. See: Using scanner.nextLine()
附录:
LinePattern
定义为 Pattern 符合此条件的code>
:
private static final String LINE_SEPARATOR_PATTERN =
"\r\n|[\n\r\u2028\u2029\u0085]";
private static final String LINE_PATTERN = ".*("+LINE_SEPARATOR_PATTERN+")|.+$";
默认令牌分隔符是此模式
:
The default token delimiter is this Pattern
:
private static Pattern WHITESPACE_PATTERN = Pattern.compile(
"\\p{javaWhitespace}+");
这篇关于为什么hasNext()为False,但hasNextLine()为True?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!