【问题标题】:addCountry nullpointer erroraddCountry 空指针错误
【发布时间】:2012-05-16 01:15:28
【问题描述】:

有人可以提供一些关于为什么代码不起作用的见解吗?

[编辑:修复代码和新错误]

我在线程“main”java.lang.NullPointerException 中收到错误异常 根据我的输出,World.addCountry()(第 8 行)代码出现错误,addWorldplaces()(第 5 行)代码出现错误。

我觉得这与不实例化 world 类有关吗?有可能吗?

public class World{

private Country[] countries;
private int numCountries=0;

public boolean addCountry(Country newCountry){
    if(!(newCountry==null)){
        countries[numCountries]=newCountry;

        numCountries++;
        return true;
    }
    else
        return false;
       }
}

public static void addWorldplaces(World pWorld){
         Country usa=new Country("USA", 1);
        pWorld.addCountry(usa);
}

【问题讨论】:

  • 戴夫在评论中有你的答案。
  • 完全不相关:你应该写if(newCountry!=null),而不是if(!(newCountry==null))。它的作用完全相同,但具有阅读速度更快的好处。

标签: java arrays nullpointerexception


【解决方案1】:

数组实际上是 Java 中的对象。您需要先分配 Countries 数组,然后才能使用它。您通常会在构造函数中执行此操作:

public class World
{
  private Country[] countries;
  private int numCountries;

  public World()
  {
    this.countries = new Country[16];       // allocate the array
    this.numCountries = 0;
  }

  ...
}

您需要适当地调整数组的大小。或者,您可以查看 ArrayList,如果需要,它会自动增大大小。

【讨论】:

  • 感谢您的建议,遗憾的是我仍然遇到同样的错误,不知道为什么..
【解决方案2】:

有两种可能:

  1. 没有实例化World对象(我没有看到pWorld第一次实例化的地方)
  2. 您的Country 数组没有实例化。你必须这样做private Country[] countries = new Country[10]

注意: 请发布异常的堆栈跟踪。

【讨论】:

    【解决方案3】:

    Greg Kopff 是对的,你必须先初始化一个数组,然后再往里面放东西。

    在你的情况下,数组的大小是不确定的,ArrayList 更好。 所以你不需要自己处理扩展数组或国家号码。

    public class World {
    
      private ArrayList<Country> countries = new ArrayList<Country>();
    
      public boolean addCountry(Country country) {
          if (country != null) {
              countries.add(country);
              return true;
          } else {
              return false;
          }
      }
    
      public int getCountryNumber() {
          return countries.size();
      }
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 2017-09-09
      相关资源
      最近更新 更多