当前位置: 代码迷 >> J2SE >> in thread "main" java.lang.StackOverflowError
  详细解决方案

in thread "main" java.lang.StackOverflowError

热度:373   发布时间:2016-04-24 18:12:47.0
二分法递归为什么会出现栈溢出的异常呢?
public class erfensort{
public static void main(String args[]){
int length = 10;
Array_erfen ef = new Array_erfen(length);
ef.insert(1);
ef.insert(2);
ef.insert(3);
ef.insert(4);
ef.insert(6);
ef.insert(7);
ef.insert(8);
ef.insert(9);
int keyWord = 5;
if(ef.erfen(keyWord,0,length-1) == -1){
System.out.println("Can Not Find The Value");
}else{
System.out.println("Hava Find The Value:" + keyWord);
}
}
}
class Array_erfen {
int[] array;
int index = 0;
public Array_erfen(int length){
array = new int[length];
}

public void insert(int value){
array[index] = value;
index++;
}
public int erfen(int keyValue,int lowBound,int uperBound){
int curIn = (lowBound+uperBound)/2;
if(lowBound > uperBound){
return -1;
}
if(array[curIn]==keyValue){
return keyValue;
}else if(array[curIn] < keyValue){
return erfen(keyValue,curIn++,uperBound);
}else{
return erfen(keyValue,lowBound,curIn--);
}

}
}
系统报错:Exception in thread "main" java.lang.StackOverflowError
请问是为什么呢???



------解决方案--------------------
Java code
public class erfensort{    public static void main(String args[]){    int length = 10;    Array_erfen ef = new Array_erfen(length);    ef.insert(1);    ef.insert(2);    ef.insert(3);    ef.insert(4);    ef.insert(6);    ef.insert(7);    ef.insert(8);    ef.insert(9);    int keyWord = 9;    if(ef.erfen(keyWord,0,length-1) == -1){    System.out.println("Can Not Find The Value");    }else{    System.out.println("Hava Find The Value:" + keyWord);        }    }    }class Array_erfen {//erfen是什么的简称,你拿你家99只猫命名,又不做注释    int[] array;    int index = 0;    public Array_erfen(int length) {    array = new int[length];    }    public void insert(int value) {    if(index>=0 && index<array.length){        array[index] = value;        index++;    }    else throw new UnsupportedOperationException("数组越界");        }        public int erfen(int keyValue, int lowBound, int highBound) {    int curIn = (lowBound + highBound) / 2;    if (lowBound > highBound) {        return -1;    }        if (array[curIn] == keyValue) {        return keyValue;    } else if (array[curIn] < keyValue) {        curIn++;////////////////////////////////////////////////////////注意Java中前置++和后置++的用法        return erfen(keyValue,curIn , highBound);    } else {        curIn--;////////////////////////////////////////////////////////注意Java中前置--和后置--的用法        return erfen(keyValue, lowBound,curIn );    }    }}
------解决方案--------------------
return erfen(keyValue,curIn++,uperBound);
return erfen(keyValue,lowBound,curIn--);
这里是不是有问题吧,改成下面应该没问题了
return erfen(keyValue,curIn+1,uperBound);
return erfen(keyValue,lowBound,curIn-1);
  相关解决方案