简体   繁体   中英

Split String input from file into an array using scanner

I have a textfile that i am reading out of that looks like this:

pizza, fries, eggs.
1, 2, 4.

I am scannning this .txt using the Scanner class and i want to insert the input into an ArrayList. I know that there is a method to split Strings and use the "," as a Delimiter but i cannot seem to find how and where to apply this. Note: The . is used as its own Delimiter so the scanner know it needs to check the next Line and add that to a different ArrayList.

Here is my corresponding code from the class with the ArrayList Setup:

public class GrocerieList {

    static ArrayList<String> foodList = new ArrayList<>();
    static ArrayList<String> foodAmount = new ArrayList<>();
}

And here is the code from the class scanning the .txt input:

public static void readFile() throws FileNotFoundException {
        Scanner scan = new Scanner(file);
        scan.useDelimiter("/|\\.");
        scan.nextLine(); // required because there is one empty line at .txt start

        if(scan.hasNext()) {
            GrocerieList.foodList.add(scan.next());
            scan.nextLine();
        }
        if(scan.hasNext()) {
            GrocerieList.foodAmount.add(scan.next());
            scan.nextLine();
        }
    }

Where can i split the strings? And how? Perhaps my approach is flawed and i need to alter it? Any help is greatly appreciated, thank you!

Use nextLine() to read a line from the file, then eliminate the ending period, and split on comma.

And use try-with-resources to close the file correctly.

public static void readFile() throws FileNotFoundException {
    try (Scanner scan = new Scanner(file)) {
        scan.nextLine(); // required because there is one empty line at .txt start
        GrocerieList.foodList.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\.$", "").split(",\\s*")));
        GrocerieList.foodAmount.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\.$", "").split(",\\s*")));
    }
}

Usually you would save the read out from the nextLine method, and use the split method to decompose the list into an array, then store it to your target. If conversion is needed, such as from string to integer, do it separately.

  String lineContent = scan.nextLine();
  String[] components = lineContent.split(","); //now your array has "pizza", "fries", "eggs" etc.

The easiest way to do this would be to use String#split. Also you don't want 'next', but nextLine

GrocerieList.foodList.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\\\.$", "").split(", ")));

(Should work but didn't test it).

For more informations about the scanner class refer to https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

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