0

I'm trying to create a string array from a .txt file passed as a parameter but I'm running into problems. Any help? Here is my code:

public String[] getStrings( String filename ){

    File sourceFile = new File(filename);
    Scanner input = new Scanner(sourceFile);
    String[] strArray;

    while(input.hasNext()){
      String s1 = input.nextLine();
      strArray = s1.toArray();
    }

    return strArray;
}
keyboardP
  • 68,824
  • 13
  • 156
  • 205
user1989233
  • 51
  • 1
  • 1
  • 2

2 Answers2

2

You've got a few issues in that method to address. First of all, whenever you're dealing with file i/o, there's almost always the risk of IOException, so you'll want to catch that somewhere. For instance, you could wrap your entire code in:

public String[] getStrings( String filename ){
    try {
        //Method content
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Second, arrays are fixed size, meaning you need to know up front how big the array would be. And since you don't know that (the file could have any number of lines), you need to use a variable size container, such as ArrayList instead.

You can declare the ArrayList as follows:

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

That will create an empty ArrayList. Now, instead of strArray = s1.toArray();, use strArray.add(s1).

Then, to convert back to an array (for your method returns an array), use strArray.toArray(new String[]{}). The new String[]{} parameter is necessary to tell the compiler that this is in fact an array of strings, not one of objects in general.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • I tried this but for some reason my compiler isn't letting me use ArrayList. We didn't learn about ArrayList so I'm not sure if we're supposed to be even using them. – user1989233 Apr 17 '13 at 03:10
  • Put `import java.util.ArrayList` at the top of your source file. Sorry I forgot to mention that. – Silvio Mayolo Apr 17 '13 at 03:13
  • This still is not working because I am still getting the compiler error that I am returning an ArrayList rather than String Array – user1989233 Apr 17 '13 at 03:45
  • Did you heed my final paragraph? You've got to return `strArray.toArray(new String[]{})` rather than just `strArray` in order to get it back to JAVA's built-in array format. – Silvio Mayolo Apr 17 '13 at 03:48
1

I think you want to use strArray.append(s1);. Otherwise you're overwriting your strArray each time, and only receiving information from the last line of the text file.

Edit: Forgot about array size :( too much web scripting for me.. this link should help. How to add new elements to an array?

Community
  • 1
  • 1
Camron
  • 308
  • 1
  • 7