Skip to content
Advertisement

Why is the useDelimiter works like that?

I have been trying to read a folder that contains any text files like this:

K.Love,CLE,miss,2
K.Leonard,TOR,miss,2
K.Love,CLE,make,1
...

I was doing some tests and for some reason when I use the useDelimeter to ignore or make the commas disappear, I encounter to a problem. I will show the code first:

import java.io.*;
import java.util.*;

public class test {
    public static void main(String[] args) throws FileNotFoundException {
        File inputFile = new File("src\main\resources\games\game1.txt");
        Scanner reader = new Scanner(inputFile);
        reader.useDelimiter(",");
        ArrayList<String> names = new ArrayList<>();
        while (reader.hasNext()) {
            String input = reader.next();
            names.add(input);
        }
        System.out.println(names.get(3));
        reader.close();
    }
}

What I expect when the console prints the arrayList at position 3 is:

K.Leonard

But instead of that it prints:

2
K.Leonard

When I change the position to number 4 it prints: TOR (Which is the name of a team).

Advertisement

Answer

You defined your delimiter as ,, meaning that the newline is no longer the delimiter. To get the behavior you expect, you could use a regex where either a , or a newline character are considered as delimiters:

reader.useDelimiter("[,n]");
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement