这是我的Superhero
类:
public class Superhero {
public int strength;
public int powerUp;
public int defaultStrength = 10;
public String name;
public Superhero(String name) {
this.strength = 10;
System.out.println("The Superheroes available are :" + name);
}
public Superhero(String name, int strength) {
if (strength >= 0) {
this.strength = strength;
System.out.println("The Superheroes available are :" + name);
} else {
System.out.println("Error. Strength cannot be < 0");
}
}
public void setStrength( int strength ) {
this.strength = strength;
}
public int getStrength() {
return strength;
}
public void powerUp(int powerUp) {
this.strength += powerUp;
}
}
这是我的 Fight
类,这里的问题是当我运行它时,我得到的获胜者结果是 null
并且我不明白为什么要这样做.
import java.io.*;
public class Fight {
public static void main (String args[]) {
Superhero gambit = new Superhero( "Gambit" );
Superhero groot = new Superhero( "Groot", 79);
System.out.println( "Gambit's strength is: " + gambit.strength);
System.out.println( "Groot's strength is: " + groot.strength);
System.out.println("The winner of the fight is: " + fight(gambit, groot));
}
static String fight(Superhero a, Superhero b)
{
if (a.strength > b.strength)
{
return a.name;
} else
{
return b.name;
}
}
}
最佳答案
看看你的构造函数:
public Superhero(String name) {
this.strength = 10;
System.out.println("The Superheroes available are :" + name);
}
这会设置实例字段strength
,但不会对name
实例字段执行任何操作。你的另一个构造函数是相同的。您需要包括:
this.name = name;
将参数的值复制到实例变量中。在两个构造函数中都执行此操作。否则,您最终只会得到 name
的默认值,即空引用。
顺便说一句,我强烈建议将您的字段设置为私有(private),并添加 getName()
方法以从您的 fight
方法中检索名称。如果强度低于 0,我也会抛出异常,而不是仅仅打印出错误消息,也我会创建不接受strength
参数只是链接到执行以下操作的参数:
public Superhero(String name) {
this(name, 10);
}
public Superhero(String name, int strength) {
if (strength < 0) {
throw new IllegalArgumentException("strength cannot be negative");
}
this.strength = strength;
this.name = name;
System.out.println("The Superheroes available are :" + name);
}
(构造函数显示的消息有点奇怪,因为它只列出一个名称,但这是另一回事。)
关于java - 不明白为什么我收到 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33175627/