gpt4 book ai didi

java - 重复使用 Scanner.hasNextLine()

转载 作者:太空宇宙 更新时间:2023-11-04 07:24:24 24 4
gpt4 key购买 nike

在我的一项作业中,我试图读取一个文件并逐行打印它。我尝试再次使用 hasNextLine 但没有成功。我试图以某种方式完成它,但我想知道是否有某种方法可以再次浏览我的文件,而无需创建新的扫描仪。

这是我的代码片段

sc = new Scanner(new File(args[0]));

while (sc.hasNextLine()) {

System.out.println(sc.nextLine());
}

我想稍后再次使用 while,但我不能这样做。有没有办法重置或将其返回顶部并再次遍历文件。

最佳答案

您可以在关闭第一个扫描仪后创建一个新的扫描仪:

sc.close();
sc = new Scanner(new File(args[0]));

// do the same thing again

关于java - 重复使用 Scanner.hasNextLine(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18787483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com