0

So I gathered tokens from multiple lines of a text file and put those tokens into an array called tokens. With this code.

    scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            if ((line = scanner.nextLine()).charAt(0) != '#') {
                tokens = line.split(",");
            }
        }

(Its all in a try catch block)

I need to put all of those String tokens into a single array, how would I do this. My new array is stringTokens [] = new String [countLines *4].

The while loop redefines the elements in tokens with each iteration, how do I save those old elements in stringTokens and add the new elements tokens will get into stringTokens as well.

m0skit0
  • 25,268
  • 11
  • 79
  • 127
user4493284
  • 21
  • 1
  • 5

2 Answers2

1

You can use an ArrayList<String> for that, and when you need it as array, you can convert it to one:

ArrayList<String> list = new ArrayList<>();
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
    if ((line = scanner.nextLine()).charAt(0) != '#') {
        for(String s : line.split(",")) {
            list.add(s);
        }
    }
}
stringTokens = list.toArray(new String[0]);
MinecraftShamrock
  • 3,504
  • 2
  • 25
  • 44
0

You should look into using ArrayLists. They are essentially mutable arrays, with no specified size (the array "grows"* as you add elements.) and adding each token to your list of strings.

ArrayList<String> stringTokens = new ArrayList<String>();

...
for(String s : line.split(",")) {
        stringTokens.add(s);
}

*Capacity doubles when needed.

rageandqq
  • 2,221
  • 18
  • 24