【问题标题】:Why am I receiving a stack overflow?为什么我会收到堆栈溢出?
【发布时间】:2019-02-25 12:31:50
【问题描述】:

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

    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)

如何找到导致堆栈溢出的位置?

【问题讨论】:

  • 您介意正确格式化您的代码吗?它将更易于阅读并帮助其他人快速扫描您的代码以查找错误。

标签: java stack-overflow


【解决方案1】:

Item 创建SlayerProgram

SlayerProgram sp = new SlayerProgram();

SlayerProgram 创建Item

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

因此在初始化时,您将无休止地创建这些对象

有一个类似的Baeldung example 用于获取 StackOverflowError

这以 StackOverflowError 告终,因为 ClassOne 的构造函数正在实例化 ClassTwo,而 ClassTwo 的构造函数又在实例化 ClassOne。

【讨论】:

  • 又名毫无根据的相互递归
  • @Marco 谢谢,你有参考链接吗?
【解决方案2】:

因为ItemSlayerProgram 类之间存在circular 依赖关系。您在SlayerProgram 类中创建了Item item = new Item(name,price,amount);,在Item 类中创建了SlayerProgram sp = new SlayerProgram();。因此,当您尝试创建Item 的对象时,它将尝试创建SlayerProgram 的对象,然后SlayerProgram 尝试创建Item 的对象,它仍然继续method stack is not full 并导致@ 987654333@.

【讨论】:

    猜你喜欢
    • 2019-01-09
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    相关资源
    最近更新 更多