Ben Foley
Ben Foley

Reputation: 21

Why does bufferedreader return null on these values?

This is my code, I am using bufferedreader to read from a file. It stores the values it reads into the array, but when i try to print out the array it returns null values. Why does this happen? Code:

BufferedReader reader = new BufferedReader(new FileReader("valid file path here"));
        int lines = 0;
        while (reader.readLine() != null) {
            lines++;
        }

        //declare and fill array
        String[] coin_names = new String[lines];
        String line; 
        int x = 0;
        while ((line = reader.readLine()) != null) {
            coin_names[x] = line;
            x++;
        }

        for (int y = 0; y < lines; y++) {
            System.out.println(coin_names[y]);
        }

Why does it return null for all of the values it gets?

Upvotes: 0

Views: 48

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522741

Here is the problem:

while (reader.readLine() != null) {
    lines++;
}

Your initial while loop is consuming the entire file. A better approach would be to remove it, and instead just use a list to store the lines:

List<String> coinNames = new ArrayList<>();
String line; 
int x = 0;
while ((line = reader.readLine()) != null) {
    coinNames.add(line);
    x++;
}

for (String name : coinNames) {
    System.out.println(name);
}

While you could try to reset the reader, there is no reason why you should have to read the entire file twice just to intialize an array. Use the right data structure for the job.

Upvotes: 3

Related Questions