-1

我正在尝试制作一个具有 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() {

}
}
4

2 回答 2

6

的每个实例为该字段Calculator创建一个。这些,反过来,创造更多,等等。new Calculator()cCalculatorsCalculators

发生这种StackOverflowError情况是因为对构造函数的这一系列调用Calculator永远不会结束,会填满所有可用的堆栈内存。看来您不需要该 nested Calculator,因此请尝试将其删除。

于 2013-04-06T00:26:09.423 回答
1

AStackOverflowError当你调用太多函数,吃掉所有可用的堆栈时会发生。递归函数调用次数过多可能会发生这种情况。例如,以下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();
    ...
}
于 2013-04-06T00:30:38.380 回答