gpt4 book ai didi

java - 为什么我的数组中的索引 0 出现 stackoverflow 错误

转载 作者:行者123 更新时间:2023-12-01 07:54:54 25 4
gpt4 key购买 nike

这是我的战士职业。我希望这个类(class)有一群战士。这个想法是能够调用这样的方法 --> Warriors.select(1) ,它将在索引 1 处创建战士。希望这是有道理的。请向我解释为什么会发生此错误。

Exception in thread "main" java.lang.StackOverflowError
at pking.Warrior.<init>(Warrior.java:42)

代码

package pking;

public class Warrior {

private String name;
private int age;
private String call;
private int attackPower;
private String weapon;

public Warrior(String myName, int myAge, String myCall, int myAttackPower) {
name = myName;
age = myAge;
call = myCall;
attackPower = myAttackPower;
weapon = "";
Warrior[] warriors = new Warrior[4];
warriors[0] = new Warrior("Spartacus", 40, "I AM SPARTACUS!", 9000);
warriors[1] = new Warrior("Crixus", 35, "CHAMPION OF CAPUA", 8000);
warriors[2] = new Warrior("Gannicus", 30, "SLAYER", 8000);
warriors[3] = new Warrior("Alexander", 21, "I AM ALEXANDER, THE CODER", 0);
}

//Prints warriors name
public void name() {
System.out.println(name);
}

//Prints warriors age
public void age() {
System.out.println(age);
}

//Prints warriors call
public void warriorsCall() {
System.out.println(call);
}

//Prints warriors attack power
public void attackPower() {
System.out.println(attackPower);
}

//Equips warriors weapon and prints message
public void equip(String myWeapon) {
weapon = myWeapon;
System.out.println("Equiped the: " + weapon);
}

//Prints warriors weapon
public void weapon() {
System.out.println(weapon);
}

}

最佳答案

当您递归调用它时,您的构造函数正在运行无限循环。检查构造函数中的这些行:

    Warrior[] warriors = new Warrior[4];
warriors[0] = new Warrior("Spartacus", 40, "I AM SPARTACUS!", 9000);
warriors[1] = new Warrior("Crixus", 35, "CHAMPION OF CAPUA", 8000);
warriors[2] = new Warrior("Gannicus", 30, "SLAYER OF VAGINAS", 8000);
warriors[3] = new Warrior("Alexander", 21, "I AM ALEXANDER, THE CODER", 0);

对于每个 Warrior 数组项实例化,您调用相同的构造函数,该构造函数再次尝试创建数组并初始化项,这种情况会一直持续下去,直到堆栈溢出。

更好的设计策略是创建一个新类,例如 Legion,其中包含 Warrior 的集合:

public class Legion {
Warrior[] warriors;

public Legion() {
warriors = new Warrior[4];
warriors[0] = new Warrior("Spartacus", 40, "I AM SPARTACUS!", 9000);
warriors[1] = new Warrior("Crixus", 35, "CHAMPION OF CAPUA", 8000);
warriors[2] = new Warrior("Gannicus", 30, "SLAYER OF VAGINAS", 8000);
warriors[3] = new Warrior("Alexander", 21, "I AM ALEXANDER, THE CODER", 0);
}

// getters and setters
}

关于java - 为什么我的数组中的索引 0 出现 stackoverflow 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31374102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com