您好,我还是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
内部内容放入其自己的类中。