3 回答

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

TA贡献1830条经验 获得超9个赞
你需要检查是否有对下一行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 个值。

TA贡献1864条经验 获得超6个赞
你的文件总是有你关心的三件事吗?如果是这样,请使用 for 循环而不是 while 循环来简化问题。这样你就不必担心尾随的换行符(这是常见的)把你搞砸了。
for(int i = 0; i < 3; i++) {
definition = scan.nextLine();
otherInfo = scan.nextLine();
link = scan.nextLine();
}
添加回答
举报