javaarraysstringtokenizer

Reading a file into Java using StringTokenizer


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

Solution

  • You're restarting your count and rewriting names on each line.

    Try creating names as an ArrayList.

    ArrayList<String> names;
    

    Initialize it once outside the first loop like this:

    names = new ArrayList<String>();
    

    Then each time you would normally put the name in the array replace this line:

    names[i] = myTokens.nextToken();
    

    With:

    names.add(myTokens.nextToken());