java - 不明白为什么我收到 null

标签 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;
  }

}

这是我的 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/

相关文章:

Java 按第三个元素对数组进行排序

java - 为什么查询谷歌云文件返回一个空列表?

java - 如何将源目录放置在eclipse中的构建路径中

java - Spring请求参数字符串-jackson

java - 如何在一定次数的执行后停止计划重复执行的 Runnable

java - 以编程方式抛出 EntityExistsException - 不好的做法?

java - 如何在 Spring 框架前端接收验证消息?

java - ORA-12705 和 ORA-00604 生产错误

java - 我可以将 Spring 框架与 swing/SET 一起使用吗?

java - Eclipse 的 Swing 设计器插件