为什么我在数组中的索引0上遇到堆栈溢出错误

0 java stack-overflow

这是我的战士班.我想在这堂课上有一系列的战士.我们的想法是能够调用这样的方法 - > warrior.select(1),它将获得在索引1处创建的战士.希望这是有意义的.请向我解释为什么会发生这种错误.

Exception in thread "main" java.lang.StackOverflowError
    at pking.Warrior.<init>(Warrior.java:42)
Run Code Online (Sandbox Code Playgroud)

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

Jun*_*san 6

当您以递归方式调用它时,构造函数正在运行无限循环.在构造函数中检查以下行:

    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);
Run Code Online (Sandbox Code Playgroud)

对于每个Warrior数组项实例化,您调用相同的构造函数,它再次尝试创建数组并初始化项,这将一直持续到堆栈溢出.

一个更好的设计策略是创建一个新类,比如说Legion,它将包含一个Warriors 的集合:

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
}
Run Code Online (Sandbox Code Playgroud)