所以这是我的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
的默认值,它是空引用。顺便说一句,我强烈建议您将字段设为私有,并添加
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/