簡體   English   中英

為什么不能兩次調用 scanEverything 方法? 它只打印一次 arrayList,第二個 println 顯示一個空列表

[英]Why is it not possible to call the scanEverything method twice? It only prints out the arrayList once, and the second println shows an empty list

我在與其他文件相同的文件夾中有一個test1.txt文件。 例如,它有以下數據: Hello Hello Hello 我的代碼只打印一次。 我調用了該方法兩次,但第二個 println 顯示了一個空的數組列表。

跑:

[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 之后,Scanner 被“消耗”,即scan.hasNext()將返回 false。

如果你想再次掃描文件,你必須重新創建掃描器(詳細信息請參見此處: Java Scanner "rewind"

您定義為“scan1”的掃描器在第一次函數調用后被消耗,您必須使用不同的掃描器或關閉第一個掃描器“scan1”並再次啟動它。

例如。

調用函數scanEverything 后使用以下

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM