开发者社区> 问答> 正文

java.lang.StackOverflowError的问题

已解决

很简单的一段代码,也知道是哪里错误,就是不明白为什么,希望大侠们指教指教
当调用main.drop(6000) 就报错了, drop(int times)方法里调用了自身的方法,这样为什么会导致报错呢

public class Main {
 private double TotalHeight = 100;
 private double CurHeight = 50;

public void drop(int times) {
 if ((times - 1) == 0) {
 return;
 }

setTotalHeight(getTotalHeight() + 2 * getCurHeight());
 setCurHeight(getCurHeight() / 2);

drop(times - 1);
 }

public double getTotalHeight() {
 return TotalHeight;
 }

public void setTotalHeight(double totalHeight) {
 TotalHeight = totalHeight;
 }

public double getCurHeight() {
 return CurHeight;
 }

public void setCurHeight(double curHeight) {
 CurHeight = curHeight;
 }

public static void main(String[] args) {
 Date startDate = new Date();

Main main = new Main();

main.drop(50000); // 此处达到6000的时候就报标题上面的错误

System.out.println("Total height is " + main.getTotalHeight());
 System.out.println("Current height is " + main.getCurHeight());
 }
 }

展开
收起
蛮大人123 2016-02-21 10:27:21 2264 0
2 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪
    采纳回答

    递归太深了,stack分配给递归的空间是有限的,如果你的递归太深,stack耗尽,就会报堆栈溢出
    我写了一个,同样是实现你这个的功能

    /**
     * 
     * @param count 弹跳次数
    * @return 返回第count次弹起的高度
    /
    public static double high(int count){
     if(count==1){return 50;}
     return high(count-1)/2;
     }
     /*
     * 
     * @param count 弹跳次数
    * @return 第count次弹跳结束时经过的路程
    */
    public static double totalHigh(int count){
     if(count==1){return 100+high(count)*2;}//第一次弹跳结束时经过的路程
    return totalHigh(count-1)+high(count-1);
     }
     public static void main(String[] args) {
     Scanner sc = new Scanner(System.in);
     System.out.print("请输入弹跳次数:");
    int count = sc.nextInt();
     System.out.println("第"+count+"次弹跳高度为:"+high(count)+"米");
    System.out.println("第"+count+"次弹完总路程为:"+totalHigh(count)+"米");
    }
    2019-07-17 18:45:45
    赞同 展开评论 打赏
  • 栈溢出抛出StackOverflowError错误,出现此种情况是因为方法运行的时候栈的深度超过了虚拟机容许的最大深度所致
    2019-07-17 18:45:45
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
OpenCrypto Unchaining the Java 立即下载
Java Your(Next) 立即下载
EXTENDING SPARK WITH JAVA AGEN 立即下载