使用 hasNextLine() 方法检查多行

我在使用该Scanner.hasNextLine()方法时遇到了问题。这是我的代码:


while(scan.hasNextLine()) {         

     definition = scan.nextLine();

     otherInfo = scan.nextLine();

     link = scan.nextLine();

}

如您所见,在 Scanner 检查是否还有另一行之后,我将三行作为输入。问题出现在我的文件末尾。 Scanner 扫描文件的最后一行并执行 while 循环,即使没有足够的行来完成循环而不抛出NoSuchElementFound异常。


有什么方法可以使用该Scanner.hasNextLine()方法检查文件中是否还有多行?感谢您的时间和您可以提供的任何帮助。


紫衣仙女
浏览 294回答 3
3回答

素胚勾勒不出你

一种解决方案是将变量放入诸如 an 之类的数据结构中ArrayList,然后执行以下操作:ArrayList<String> arr = new ArrayList<>();while(scan.hasNextLine()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; arr.add(scan.nextLine());}这样您就可以确保有下一行并且您不必对分配变量进行硬编码。那么arr[0]将会是definition,arr[1]将会是otherInfo,arr[2]将会是link

慕标琳琳

你需要检查是否有对下一行otherInfo和link,在检查definition中做到while (scan.hasNextLine()):while(scan.hasNextLine()) {&nbsp; &nbsp; definition = scan.nextLine();&nbsp; &nbsp; if (scan.hasNextLine()) {&nbsp; &nbsp; &nbsp; &nbsp; otherInfo = scan.nextLine();&nbsp; &nbsp; &nbsp; &nbsp; if (scan.hasNextLine())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; link = scan.nextLine();&nbsp; &nbsp; }}但问题是你从这个循环中得到了什么?只是阅读行而不保存它们,或打印它们?循环在某个时刻结束,3 个变量有它们的最后 3 个值。

慕尼黑的夜晚无繁华

你的文件总是有你关心的三件事吗?如果是这样,请使用 for 循环而不是 while 循环来简化问题。这样你就不必担心尾随的换行符(这是常见的)把你搞砸了。for(int i = 0; i < 3; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; definition = scan.nextLine();&nbsp; &nbsp; otherInfo = scan.nextLine();&nbsp; &nbsp; link = scan.nextLine();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java