【问题标题】:Java NullPointerException while using array [duplicate]使用数组时出现Java NullPointerException [重复]
【发布时间】:2025-12-21 17:20:18
【问题描述】:

当我尝试执行“temperaturEingeben”方法时,为什么会出现 NullPointerException? 我希望你能理解我的代码,因为它是德文的。

public class Temperaturanzeige{                                 
    private int[] temperatur;                                   

    public Temperaturanzeige(){                                 
        int[] temperatur=new int[24];                           
        for(int i=0; i<temperatur.length;i++){                  
            temperatur[i]=-100;
        }

    }

    public void temperaturEingeben(int tempNeu,int tageszeit){
        temperatur[tageszeit]=tempNeu;
    }

}

感谢您的回答!

【问题讨论】:

  • 你确定是 NullPointerException 而不是 IndexOutOfBoundsException?
  • 您永远不会在任何地方设置字段temperatur。是的,有一个同名的局部变量,但这只会影响字段。
  • @JohannesKuhn 可能是一个骗子,但那个太通用了,无法使用。我扫描了最上面的 3 个答案,但没有包含问题。
  • 如果出现小错误则关闭。

标签: java arrays nullpointerexception


【解决方案1】:
int[] temperatur=new int[24];

创建一个新变量,删除int[]

【讨论】:

  • 感谢您的回答!
【解决方案2】:

您在构造函数中创建一个新变量,而不是分配一个变量。改变这个:

int[] temperatur=new int[24];  

到这里:

this.temperatur = new int[24];  

【讨论】: