简体   繁体   中英

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

I have a test1.txt file in the same folder as the rest of the files. Say, for instance, it has the following data: Hello Hello Hello My code only prints this once. I called the method twice, but the second println shows an empty arraylist.

run:

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

Code:

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;
    }

After your call to scanEverything, the Scanner is "consumed", ie the scan.hasNext() will return false.

If you want to scan the file again, you have to recreate the Scanner (see here for details: Java Scanner "rewind" )

Scanner that you defined as "scan1" got consumed after first function call you have to use different Scanner or close the first scanner that is "scan1" and initiate it again.

For eg.

After calling function scanEverything use below lines

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM