Java 主实例化两个对象时出现堆栈溢出错误?

Java 主实例化两个对象时出现堆栈溢出错误?,java,Java,您好,我还是Java和OOP新手,在尝试编译代码时遇到了问题。我理解我的代码的问题是同一个对象的实例化两次,但是我不确定如何解决这个问题来编译我的代码 package week2; import java.util.* public class aBug { aBug theBug = new aBug(); String Inspecies, Inname; int Inx, Iny, Inenergy, Inid; char Insymbol;

您好,我还是Java和OOP新手,在尝试编译代码时遇到了问题。我理解我的代码的问题是同一个对象的实例化两次,但是我不确定如何解决这个问题来编译我的代码

package week2;

import java.util.*

public class aBug {

    aBug theBug = new aBug();
    String Inspecies, Inname;
    int Inx, Iny, Inenergy, Inid;
    char Insymbol;

    Scanner scan = new Scanner(System.in);
    aWorld newWorld = new aWorld();

    public static void main(String[] args) {
        aBug theBug = new aBug();


        theBug.mainMenu();

    }

    public void mainMenu() {

        int choice;
        do {

            System.out.print("1\t Create bug\n");
            System.out.print("2\t Enter world\n");
            System.out.print("3\t Quit\n");
            choice = scan.nextInt();
            switch (choice) {

            case 1:
                bugInit();
                break;

            case 2:
                System.out.println();
                newWorld.mapInit(theBug.Inx, theBug.Iny, theBug.Insymbol);
                System.out.println();
                break;
            }
        } while (choice != 3);
    }

    public void bugInit() {
        String species, name;
        int x, y, energy, id;
        char symbol;



        System.out.print("Species: ");
        species = scan.nextLine();

        System.out.print("Name: ");
        name = scan.nextLine();

        System.out.print("X position: ");
        x = scan.nextInt();

        System.out.print("Y position: ");
        y = scan.nextInt();

        System.out.print("Energy: ");
        energy = scan.nextInt();

        System.out.print("ID: ");
        id = scan.nextInt();

        theBug.Insymbol = 'b';
        theBug.Inspecies = species;
        theBug.Inname = name;
        theBug.Inx = x;
        theBug.Iny = y;
        theBug.Inenergy = energy;
        theBug.Inid = id;

        System.out
                .format("\nThe bug is of the species %s, called %s, "
                        + "with positions %d & %d, with energy amount: %d, and %d as it's id number\n\n",
                        theBug.Inspecies, theBug.Inname, theBug.Inx, theBug.Iny,
                        theBug.Inenergy, theBug.Inid);

    }


}

在构造函数中,您有:

public class aBug {
    aBug theBug = new aBug();
...
}
因此,在创建
aBug
(例如在
main
中)的实例时,您可以调用
new aBug()
,它会在堆栈溢出的情况下再次调用构造函数


我不知道为什么您认为需要在对象本身中创建对象的实例。所以很难给出任何提示。如果我猜对了,你把
aBug
和“主程序”的概念合并到一个类中。您应该将其拆分并将
aBug
内部内容放在自己的类中。

发布您得到的错误堆栈。线程“main”java.lang.StackOverflowerr中的异常在week2.aBug.(aBug.java:6)在week2.aBug.(aBug.java:6)在week2.aBug.(aBug.java:6)在week2.aBug.(aBug.java:6)在week2.aBug.(aBug.java:6)