为什么我会收到堆栈溢出?

时间:2019-02-24 12:07:53

标签: java stack-overflow

我的第一段代码是我的项目对象文件;第二个是主班。在运行代码没有任何问题之前,但是在我添加了一个读写文件之后,我的代码开始收到堆栈流错误。只是正在调用错误的代码段。

    public class Item implements java.io.Serializable {

    public static String name;
    public static double price;
    public static double amount;
    public int max = 1;
    SlayerProgram sp = new SlayerProgram();
    ReadFile rf = new ReadFile();
    public Item(String name, double price,double amount )
    {
    this.name = name;
    this.price = price;
    this.amount = amount;

    }

    public void ItemSet(String name, double price,double amount)
    {
    this.name = name;
    this.price = price;
    this.amount = amount  
    }

我的主班:

    public class SlayerProgram {
//import file txts, and Item Class

        static String name;
        static double price;
        static double amount;
 Item item = new Item(name,price,amount);
ReadFile rf = new ReadFile();
static String fileNameText = "D:\\Game\\SlayerProgram\\Name.txt";
static String filePriceInt = "D:\\Game\\SlayerProgram\\Price.txt";
static String fileAmountInt ="D:\\Game\\SlayerProgram\\Amount.txt";

   //begin file Read   

public void BeginText() throws IOException
{
    TextFile();
}

public void Max()
{
    item.Max();
}

    //declare needed Data Types;
        final int max = item.max;
        ArrayList<String> Name  = new ArrayList<>();
        ArrayList<Double> Price = new ArrayList<>();
        double size = Price.size();
        ArrayList<Double> Amount = new ArrayList<>();


Exception in thread "main" java.lang.StackOverflowError
at slayerprogram.Item.<init>(Item.java:18)
at slayerprogram.SlayerProgram.<init>(SlayerProgram.java:25)
at slayerprogram.Item.<init>(Item.java:18)
at slayerprogram.SlayerProgram.<init>(SlayerProgram.java:25)

如何找到导致堆栈溢出的地方?

2 个答案:

答案 0 :(得分:6)

Item创建SlayerProgram

SlayerProgram sp = new SlayerProgram();

然后SlayerProgram创建Item

Item item = new Item(name,price,amount);

因此,在初始化时,您将不断创建这些对象

有类似的Baeldung example用于获取StackOverflowError

  

由于ClassOne的构造函数实例化ClassTwo,而ClassTwo的构造函数再次实例化ClassOne,因此最终出现StackOverflowError。

答案 1 :(得分:1)

因为在circularItem类之间存在SlayerProgram依赖性。您已经在类Item item = new Item(name,price,amount);中创建了SlayerProgram,并在类SlayerProgram sp = new SlayerProgram();中创建了Item。因此,当您尝试创建Item的对象时,它将尝试创建SlayerProgram的对象,然后SlayerProgram尝试创建Item的对象,并且仍然继续method stack is not full并指向StackOverflow