0

I'm working on a program that reads data from a file and inputs it into an array. It seems like it should work, however I get an odd output from the program (no error, it runs, just gives me a weird result).

Here's my code:

    Scanner s = new Scanner(new File("../Computer/src/computers/computer.txt"));
    String[] comps = new String[2];

    int i = 0;

    while (s.hasNextLine()) {
        comps[i] = s.nextLine();
        i++;
    }
    s.close();

    System.out.println(comps);

The output that I get is:

[Ljava.lang.String;@3d62b333
BUILD SUCCESSFUL (total time: 1 second)

Also, my text file looks like this, if it's a problem with my text file:

12344555 Dell Intel 499.99
23623626 Asus AMD 299.99

2 Answers 2

4

You can't print an array like that. The output you're getting is the default toString() from Object which outputs the hashcode.

You have to iterate through it and print each String

for (String s : comps)
{
    System.out.println(s);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You are reading file correctly, but printing array in incorrect way.

Use below to print your array.

    for(int j =0;j<comps.length;j++)
    {
        System.out.println(comps[j]);
    }

1 Comment

Thanks a lot, that was a big help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.