简体   繁体   English

如何解决此空指针异常错误(Java)?

[英]How do i resolve this null pointer exception error (Java)?

I am creating a project on bluej based on a gym system. 我正在基于健身系统在bluej上创建一个项目。 There is one parent class in the project which is named "Card" the child classes to this parent class include Loyalty, Standard and staff, which are all types of cards the gym system can hold.The System also has a number of Zones eg pool, sauna etc.There is also a sitemanager class which holds all the gyms information such as how many doors there are and the details of the zones. 项目中有一个名为“ Card”的父类,该父类的子类包括Loyalty,Standard和staff,它们是Gym系统可以容纳的所有类型的卡。该系统还具有多个区域,例如游泳池,桑拿浴室等。还有一个sitemanager类,其中包含所有体育馆信息,例如,有多少扇门以及区域的详细信息。

While running an IO class named centreIO, while attempting to run this part of the code; 在运行名为centerIO的IO类时,尝试运行代码的这一部分;

 private void addCard()
    {
        System.out.println("Enter card id:");
        int id = reader.nextInt();
        Card cr = hatfield.getCard(id);
        hatfield.addCard(cr);


        }

I came across a problem which pointed towards a method in the zones class. 我遇到了一个问题,该问题指向zones类中的方法。 This was the method that the null exception pointed to 这是null异常所指向的方法

public void addCardtoZone(Card C)

{

    cards.put(C.getId(),C);

}

The site manager has two Hashmaps with Zones and Doors, and Zones has a hashmap of all cards currently within the Zone, so it will hold methods such as stating how many cards are currently in the zone etc. How do I fix this code so that it actually adds the card to the the site? 站点管理器有两个带有“区域”和“门”的哈希图,“区域”具有该区域中当前所有卡的哈希图,因此它将保存诸如说明区域中当前有多少卡等方法。如何修复此代码,以便它实际上将卡添加到该网站吗? I dont understand why this is not working because when I run the method from within the Zone class it works perfectly. 我不明白为什么这不起作用,因为当我从Zone类中运行该方法时,它可以完美地工作。

Here is the method im calling on in the IO class 这是我在IO类中调用的方法

public void addCard(Card cd)
{

    Outside.addCardtoZone(cd);

}

EDIT: the put methods puts a key and an object into the hashmap 编辑:put方法将一个键和一个对象放入哈希图中

private HashMap cards = new HashMap<Integer,Card>();

And here is a sample of the card class( a superclass to 3 other classes, Loyalty, standard, staff.) 这是卡类的示例(忠诚度,标准,职员等3个其他类的超类。)

public class Card
{
public String name;

public int rating;
public int credits;
public String centre;
public int type;

//Public constructor
public Card(String nam, int rat, int cred)
{

    name = nam;
    rating = rat;
    credits = cred;


}

public int getId() //getId() has been overridden in the child classes
{

    return 0;

}

public String getName()
{
    return name;
}  

/** returns member's rating
 * @return member's rating
 */
public int getRating()
{
    return rating;
}

/** changes a member's rating
 * @param rat new rating 
 */
public void changeRating(int rat)
{
    rating = rat;
}



}

} }

public void addCardToZone(Card C) {
    if(cards == null) {
        cards = new HashMap<Integer, Card>();
    }
    cards.put(C.getId(),C);
}

Now your addCardToZone method will check cards for null . 现在,您的addCardToZone方法将检查cards是否为null If it's null , it will initialize it. 如果为null ,它将对其进行初始化。 After this, you just put a card in as normal. 之后,您只需照常put卡即可。 The if should only enter on the first call to addCardToZone . if仅在第一次调用addCardToZone输入addCardToZone

Rather than telling you what the solution is (which is a bit difficult since we can't see all of the source code that could be relevant ...), here's how to diagnose this. 而不是告诉您解决方案是什么(这有点困难,因为我们看不到所有可能相关的源代码...),而是如何诊断这一点。

1) Use the stacktrace to identify the line of code that throws the NPE. 1)使用stacktrace识别引发NPE的代码行。

You've identified it as: 您已将其标识为:

  cards.put(C.getId(),C);

2) Figure out what could cause an NPE. 2)找出可能导致NPE的原因。

In this case, there are only two possible causes: 在这种情况下,只有两种可能的原因:

  • If cards is null then cards.put will throw an NPE. 如果cardsnullcards.put将抛出一个NPE。
  • If c is null then c.getId() will throw an NPE. 如果cnullc.getId()将引发NPE。

3) Eliminate the cases that are logically impossible ... in the context. 3)在上下文中消除逻辑上不可能的情况。

For example, if cards was declared as final and you had initialized it to a non-null value then you could eliminate that possible cause. 例如,如果将cards声明为final并且已将其初始化为非null值,则可以消除这种可能的原因。 Or if in a previous statement you can used the c variable in a way that would have failed if it was null, you could eliminate that. 或者,如果在上一条语句中可以以某种方式使用c变量(如果该变量为null则失败),则可以消除该变量。

4) Work backwards through the code repeating 3) ... 4)向后遍历重复的代码3)...

5) If that fails, either use a debugger or judicious logging / trace-printing to eliminate possible causes or confirm suspicions. 5)如果失败,请使用调试器或明智的日志记录/跟踪打印来消除可能的原因或确认可疑之处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM