Java: Trouble creating an array from file

Hey I have this code here:

public class Levels {
boolean newGame = true;

public void newGame() {
    while (newGame) {
        int cLevel = 1;

        List<String> list = new ArrayList<String>();

        try {
            BufferedReader bf = new BufferedReader(new FileReader(
                    "src/WordGuess/ReadFile/LevelFiles/Level_" + cLevel
                            + ".txt"));
            String cLine = bf.readLine();
            while (cLine != null) {
                list.add(cLine);
            }
            String[] words = new String[list.size()];
            words = list.toArray(words);
            for (int i = 0; i < words.length; i++) {
                System.out.println(words[i]);
            }

        } catch (Exception e) {
            System.out
                    .println("Oh! Something went terribly wrong. A team of highly trained and koala-fied koalas have been dispatched to fix the problem. If you dont hear from them please restart this program.");
            e.printStackTrace();
        }
    }
}}

And it gives me this error:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Unknown Source) at java.util.Arrays.copyOf(Unknown Source) at java.util.ArrayList.grow(Unknown Source) at java.util.ArrayList.ensureExplicitCapacity(Unknown Source) at java.util.ArrayList.ensureCapacityInternal(Unknown Source) at java.util.ArrayList.add(Unknown Source) at WordGuess.ReadFile.SaveLoadLevels.Levels.newGame(Levels.java:24) at Main.main(Main.java:29)

Can anyone help, please? Thank you!

Jon Skeet
people
quotationmark

This is the problem:

String cLine = bf.readLine();
while (cLine != null) {
    list.add(cLine);
}

You're not reading the next line in your loop (the value of cLine never changes) - so it's just going to loop forever. You want:

String line;
while ((line = bf.readLine()) != null) {
    list.add(line);
}

(And as noted in comments, this is also in an infinite outer loop because newGame will stay true forever...)

people

See more on this question at Stackoverflow