嘿,我这里有这个代码:
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();
}
}
}}
它给了我这个错误:
线程“main”中的异常java.lang.OutOfMemoryError:Java堆空间 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) 在WordGuess.ReadFile.SaveLoadLevels.Levels.newGame(Levels.java:24) 在Main.main(Main.java:29)
有人可以帮忙吗?谢谢!
答案 0 :(得分:3)
这是问题所在:
String cLine = bf.readLine();
while (cLine != null) {
list.add(cLine);
}
你没有阅读循环中的下一行(cLine
的值永远不会改变) - 所以它只是永远循环。你想要:
String line;
while ((line = bf.readLine()) != null) {
list.add(line);
}
(正如评论中所指出的,这也是一个无限的外循环,因为newGame
将永远保持真实......)
答案 1 :(得分:1)
您正在阅读一行并继续将其添加到导致内存不足的列表中 将代码修改为:
String cLine
while(cLine = bf.readLine() != null)
{
list.add(cLine);
}