制作基本计算器时出现堆栈溢出错误

时间:2013-04-06 00:20:35

标签: java calculator stack-overflow

我正在尝试制作一个具有4个功能的计算器,这是基于单词的。当我尝试实现操作选择时,我收到stackoverflow错误。

班级计算器:

package us.plexproductions.main;

import java.util.Scanner;

public class Calculator {

public static int firstnum;
public static int secondnum;
public static int answer;
public static int operation;

Calculator c = new Calculator();
static Scanner s = new Scanner(System.in);

static Operations o = new Operations();

public static void main(String[] args) {

    prompt();
    start();
}

public static void prompt() {
    System.out.println("########################");
    System.out.println("#Calculator Version 1.0#");
    System.out.println("########################");
    System.out.println("************************");
    System.out.println("This is a calculator that\ncan add, subtract, multiply, and divide\n" +
                       "multiple numbers at once.");
    System.out.println("------------------------");
    System.out.println("Start Calculating by Entering A Number and Then\nspelling out the operation you " +
                       "want to preform to that\nnumber and type in another number.");
}

public static void start() {
    System.out.println("------------------------");
    System.out.println("Enter Your First Number: ");
    firstnum = s.nextInt();
    System.out.println("------------------------");
    System.out.println("Which operation would you like to use?\nAddition = 1, Subtraction = 2, Multiplication = 3, or Division = 4?");
    operation = s.nextInt();
    second();

}

public static void second() {
    if (operation == 1) {
        o.addition();
    }
    if (operation == 2) {
        o.subtraction();
    }
    if (operation == 3) {
        o.multiplication();
    }
    if (operation == 4) {
        o.division();
    }
}
}

班级操作:

package us.plexproductions.main;

import java.util.Scanner;

public class Operations {

Calculator c = new Calculator();
Scanner s2 = new Scanner(System.in);

public void addition() {
    System.out.println("Addition Selected.");
    System.out.println("Enter Second Number: ");
    Calculator.secondnum = s2.nextInt();
}

public void subtraction() {

}

public void multiplication() {

}

public void division() {

}
}

2 个答案:

答案 0 :(得分:6)

Calculator的每个实例都会为字段new Calculator()创建c。反过来,这些Calculators会创建更多Calculators,依此类推。

StackOverflowError发生,因为对Calculator构造函数的这一系列调用永远不会结束,从而填满所有可用的堆栈内存。您似乎需要嵌套Calculator,因此请尝试将其删除。

答案 1 :(得分:1)

当您调用太多函数时,会发生StackOverflowError,并且可以使用所有可用的stack。它可能发生在被称为太多次的递归函数中。例如,以下factorial函数在我的机器上溢出:

public class Factorial {
    public static int factorial(int n){
        if (n == 1) return 1;
        return n * factorial(n-1);
    }

    public static void main(String[] args){
        factorial(10000);
    }
}

现在,您在代码中使用递归在哪里?

public class Calculator{
    Calculator c = new Calculator();
    ...
}