不明白为什么我收到null

0 java

所以这是我的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;
  }

}
Run Code Online (Sandbox Code Playgroud)

这是我的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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

看看你的构造函数:

public Superhero(String name) {
   this.strength = 10;
   System.out.println("The Superheroes available are :" + name);
}
Run Code Online (Sandbox Code Playgroud)

这会设置实例字段strength,但不会对实例字段执行任何操作name.你的其他构造函数是一样的.你需要包括:

this.name = name;
Run Code Online (Sandbox Code Playgroud)

将参数中的值复制到实例变量中.在两个构造函数中执行此操作.否则,您最终会得到默认值for 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);
}
Run Code Online (Sandbox Code Playgroud)

(构造函数显示的消息有点奇怪,因为它只列出了一个名称,但这是另一回事.)