创建字符串的程序中的Java OutOfMemoryError

时间:2016-01-20 08:19:57

标签: java

我正在回答codingbat question,但是当我运行我的代码时,我收到此错误:

Well done the answer is, Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3332)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:137)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:121)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:421)
at java.lang.StringBuilder.append(StringBuilder.java:136)
at CodingBat.extraFront(CodingBat.java:24)
at CodingBat.main(CodingBat.java:7)

我的代码是:

public class CodingBat {


public static void main(String[] args){
    CodingBat object = new CodingBat();
    System.out.print("Well done the answer is, ");
    System.out.print(object.extraFront("Test"));          

}




public String extraFront(String str) {
    int x = 1;
    String string;
    if(str.length() == 0)
        return "";
    else if(str.length() == 1)
        string = str.substring(0,1);
    else
        string = str.substring(0,2);
    while(x <= 2){
        string += string;
    }
    return string;
}


}

2 个答案:

答案 0 :(得分:4)

你有一个无限循环,一直在创建更长和更长的字符串,直到你的内存不足为止:

while(x <= 2){
    string += string;
}

由于您的条件取决于x,您可能希望在while循环内增加x(或者使用for循环):

while(x <= 2){
    string += string;
    x++;
}

for (int x = 1; x <= 2; x++) { // remove the previously declared x variable
    string += string;
}

答案 1 :(得分:2)

问题来自永不退出的循环。

while(x<=2){
    // whatever
    x++;
}

它会将字符串堆叠起来,直到内存中断。