亲爱的,我想实现这种行为:
"闯入者将被枪杀,幸存者将再次被枪杀"
但是我得到了这个堆栈跟踪:
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上。
答案 0 :(得分:10)
return !name.equals("Chuck Norris");
总是返回false因此你无限循环。
你的弹药可能有限,所以你应该考虑某种弹药功能。
答案 1 :(得分:4)
您的错误发生在您的Person Constructor中。添加条款
if(name.equals("Chuck Norris")){
throw new ChuckNorrisException("Chuck Norris saw through your ploy to consider him a person");
}
然后你会没事的。
答案 2 :(得分:3)
在以下代码段中,您在此人活着时循环shoot
。由于查克诺里斯不能死,你最终无限制地射击他,他最终用StackOverflowError
杀死你的程序:
public void shoot(Person person) {
if(!person.isDead()){
shoot(person);
}
}
您可以设置最大弹药数量或添加firstShot
参数以仅允许2次射击。例如:
public void shoot(Person person) {
shoot(person, true);
}
private void shoot(Person person, boolean firstShot) {
if(firstShot && !person.isDead()) {
shoot(person, false);
}
}