【问题标题】:Java: Trouble creating an array from fileJava:从文件创建数组时遇到问题
【发布时间】:2014-02-19 22:34:48
【问题描述】:

嘿,我这里有这段代码:

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();
        }
    }
}}

它给了我这个错误:

线程“主”java.lang.OutOfMemoryError 中的异常:Java 堆空间 在 java.util.Arrays.copyOf(未知来源) 在 java.util.Arrays.copyOf(未知来源) 在 java.util.ArrayList.grow(未知来源) 在 java.util.ArrayList.ensureExplicitCapacity(未知来源) 在 java.util.ArrayList.ensureCapacityInternal(未知来源) 在 java.util.ArrayList.add(未知来源) 在 WordGuess.ReadFile.SaveLoadLevels.Levels.newGame(Levels.java:24) 在 Main.main(Main.java:29)

有人可以帮忙吗?谢谢!

【问题讨论】:

  • 您正在阅读的文件有多大?当您的计算机内存不足时抛出 java.lang.OutOfMemoryError,因为您正在使用 Java 运行非常繁重的程序。
  • @migueljimenezz:在这种情况下,文件的长度无关紧要,只要至少有一行 - 请参阅我的回答 :)
  • newGame 在哪里设置为 false?我在这里看到的是一个无限循环!

标签: java arrays arraylist bufferedreader filereader


【解决方案1】:

这就是问题所在:

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

您没有读取循环中的下一行(cLine 的值永远不会改变) - 所以它只会永远循环。你想要:

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

(如 cmets 中所述,这也是无限外循环,因为 newGame 将永远保持真实......)

【讨论】:

  • Alexis Lecrec G.S 谢谢你们,伙计们!你们都是对的!我现在还没有创建我的虚假陈述并将 while 更改为 if。你真的帮了我 readLine() 声明。我认为该方法通读所有行,但现在我想通了。我多么愚蠢,它说 readLINE 就像一行一样。很抱歉用这些简单的东西打扰你。如果我可以评价你,我是新手,请告诉我如何:) 如果你能告诉我我的代码结构是否适合现在的猜字游戏,那也将不胜感激。再次感谢您!
  • 别担心,我们都是从简单的东西开始的;)
【解决方案2】:

您正在阅读一行并继续将其添加到导致内存不足的列表中。
修改你的代码为:

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

【讨论】:

    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    相关资源
    最近更新 更多