1

I am trying to read into a file, make it into an array and print it.

I'm not sure what I'm doing wrong with this code. I've been trying to get a solution but all the solutions I can find are more advanced than what we should be using...I wrote a previous program using the same method but as a Double array. I can't seem to make it work for a String?

I keep getting [Ljava.lang.String;@3d4eac6 when I run it.

I just want it to print boysNames. boyNames.txt is just a list of 200 names in a text file.

Someone please help me, or let me know if this is possible?

this is my code so far

public static void main(String[] args) throws FileNotFoundException {



    String[] boyNames = loadArray("boyNames.txt");
    System.out.println(boyNames);
}

public static String[] loadArray(String filename) throws FileNotFoundException{
    //create new array
    Scanner inputFile = new Scanner(new File (filename));
    int count = 0;
    //read from input file (open file)
    while (inputFile.hasNextLine()) {
        inputFile.nextLine();
        count++;
    }
    //close the file
    inputFile.close();

    String[] array = new String[count];
    //reopen the file for input
    inputFile = new Scanner(new File (filename));
    for (int i = 0; i < count; i++){
        array[i] = inputFile.nextLine();            
    }
    //close the file again
    inputFile.close();
    return array;
}

`

Scinder
  • 13
  • 4
  • `[Ljava.lang.String;@3d4eac6` ... this looks like you are trying to print out an array. Your code actually looks OK to me. What is the error? – Tim Biegeleisen Sep 25 '16 at 04:27
  • That is what's weird...It compiles for me, but when I run it, it just prints " [Ljava.lang.String;@3d4eac6 " – Scinder Sep 25 '16 at 04:32

1 Answers1

0

Java arrays don't override Object.toString(), so you get a generic [Ljava.lang.String;@3d4eac6 (or similar) when you try to print it out using System.out.println(). Instead loop over the array and print each value.

for (String boyName : boyNames) {
    System.out.println(boyName);
}

Alternatively, you could use Arrays.toString():

System.out.println(Arrays.toString(boyNames));

Another alternative would be to use String.join() (new for Java 8)

System.out.println(String.join("\n", boyNames));
Asaph
  • 159,146
  • 25
  • 197
  • 199