我在Scanner.hasNextLine()
方法上遇到麻烦。这是我的代码:
while(scan.hasNextLine()) {
definition = scan.nextLine();
otherInfo = scan.nextLine();
link = scan.nextLine();
}
如您所见,在扫描程序检查是否还有另一行之后,我将三行作为输入。问题出现在我的文件末尾。扫描程序将扫描文件的最后一行,并执行while循环,即使没有足够的行来完成循环而又不会引发NoSuchElementFound
异常。
是否可以使用Scanner.hasNextLine()
方法检查文件中是否还有多行?感谢您的宝贵时间和提供的任何帮助。
答案 0 :(得分:1)
一种解决方案是将变量放入ArrayList
之类的数据结构中,然后执行以下操作:
ArrayList<String> arr = new ArrayList<>();
while(scan.hasNextLine()) {
arr.add(scan.nextLine());
}
这样,您可以确保存在下一行,而不必对分配变量进行硬编码。
那么arr[0]
将是definition
,arr[1]
将是otherInfo
,而arr[2]
将是link
答案 1 :(得分:0)
您需要检查otherInfo
和link
是否存在下一行,对definition
的检查是在while (scan.hasNextLine())
中完成的:
while(scan.hasNextLine()) {
definition = scan.nextLine();
if (scan.hasNextLine()) {
otherInfo = scan.nextLine();
if (scan.hasNextLine())
link = scan.nextLine();
}
}
但是问题是您要从这个循环中做什么?
只是阅读行而不保存它们,还是打印它们?
循环在某个点结束,这3个变量的最后3个值。
答案 2 :(得分:0)
您的文件是否总是包含您真正关心的三件事?如果是这样,请使用for循环而不是while循环来简化问题。这样,您就不必担心尾随换行符(这很常见)会惹恼您。
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET /headlines/ign --> main.main.func1 (3 handlers)
[GIN-debug] GET /headlines/polygon --> main.main.func2 (3 handlers)
[GIN-debug] GET /headlines/techcrunch --> main.main.func3 (3 handlers)
[GIN-debug] Listening and serving HTTP on 35.237.89.107:8080
[GIN-debug] [ERROR] listen tcp 35.237.89.107:8080: bind: cannot assign requested address