I'm trying to do a very simple task but I'm not getting the results I want. I have a text file with names separated by a comma on multiples lines and I want to store that information in a 1D array. When I run my code and try to print the array to make sure my information was recorded the console only prints out the last line of the text file. What is wrong with my code? I've tried playing around with it but I've found no solution to my problem. Is the information being overwritten?
import java.util.*;
public class Tokens {
public static TextFileInput myFile;
public static StringTokenizer myTokens;
public static String name;
public static String[] names;
public static String line;
public static void main(String[] args) {
myFile = new TextFileInput("namesofstudents.txt");
while ((line = myFile.readLine())!= null) {
int i=0;
myTokens = new StringTokenizer(line, ",");
names = new String[myTokens.countTokens()];
while (myTokens.hasMoreTokens()){
names[i] = myTokens.nextToken();
i++;
}
}
for (int j=0;j<names.length;j++){
System.out.println(names[j]);
}
}
}
example of an input:
Mark, Joe, Bob
James, Jacob, Andy, Carl
output:
James
Jacob
Andy
Carl