gpt4 book ai didi

java - 简单程序中的 StackOverflowError

转载 作者:行者123 更新时间:2023-11-29 09:35:24 25 4
gpt4 key购买 nike

亲爱的,我想实现这个行为:

“闯入者枪毙,幸存者再枪毙”

但是我得到了这个堆栈跟踪:

Exception in thread "main" java.lang.StackOverflowError
at java.lang.String.equals(String.java:975)
at test.Person.isDead(Person.java:14)
at test.Shooter.shoot(Shooter.java:7)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)
at test.Shooter.shoot(Shooter.java:8)

“属性”类:

package test;

public class Property {

private Shooter shooter = new Shooter();

public void punish(Person tresspasser) {

shooter.shoot(tresspasser);
}
}

射手类:

package test;

public class Shooter {

public void shoot(Person person) {

if(!person.isDead()){
shoot(person);
}
}
}

“人”类:

package test;

public class Person {

private String name;

public Person(String name) {

this.name = name;
}

public void tresspass(Property property) {

property.punish(this);
}

public boolean isDead(){

return !name.equals("Chuck Norris");
}
}

最后是主类:

package test;

public class Main {

public static void main(String args[]) {

Person person = new Person("Chuck Norris");

Property myProperty = new Property();

person.tresspass(myProperty);
}
}

我做错了什么?

我使用 eclipse,问题出现在 Java 6、7 和 8 中...

S.

最佳答案

return !name.equals("Chuck Norris"); 如果此人的名字是“Chuck Norris”,则始终返回 false,因此您会无限循环。

您的弹药可能有限,因此您应该考虑某种弹药功能。

关于java - 简单程序中的 StackOverflowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36801652/

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