为什么不能调用scanEverything方法两次?它只打印一次arrayList,第二次打印ln显示一个空列表



我有一个test1.txt文件与其他文件位于同一文件夹中。例如,假设它有以下数据:HelloHelloHello我的代码只打印一次。我调用了该方法两次,但第二次println显示了一个空的arraylist。

运行:

[hello, hello, hello]
[]
BUILD SUCCESSFUL (total time: 0 seconds)

代码:

import java.io.*;
import java.util.*;
public class Text {
public static void main(String[] args) throws FileNotFoundException {

Scanner keyboard = new Scanner(System.in);
String firstFileName = "test1.txt";
Scanner scan1 = new Scanner(new File(firstFileName));

System.out.println(scanEverything(scan1));
System.out.println(scanEverything(scan1));
}
public static ArrayList<String> scanEverything(Scanner scan) {
ArrayList<String> text = new ArrayList<>();
while (scan.hasNext()) {
String nextWord = scan.next().toLowerCase();
text.add(nextWord);
}
Collections.sort(text);
return text;
}

调用scanEverything后,扫描仪将"消耗";,即CCD_ 1将返回false。

如果你想再次扫描文件,你必须重新创建扫描仪(请参阅此处了解详细信息:Java扫描仪"倒带"(

您定义为"的扫描仪;scan1">在第一次函数调用后被消耗,您必须使用不同的扫描仪或关闭";scan1">并再次启动它。

例如

调用函数后scanEverything使用以下行

scan1.close();
scan1 = new Scanner(new File(firstFileName));

最新更新