简体   繁体   中英

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!

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...)

You are reading one line and keep on adding it to list which is causing out of memory.
Modify your code as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM