0

Why do I get a NullPointerException, when I try to execute the method "temperaturEingeben"? I hope you can understand my code because it´s in German.

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

}

Thanks for your answer!

flixx10
  • 13
  • 1
  • 1
    Are you sure it's NullPointerException and not IndexOutOfBoundsException? – Lkopo Mar 31 '20 at 21:42
  • 1
    You never set the field `temperatur` anywhere. Yeah, there is a local variable with the same name, but that only shadows the field. – Johannes Kuhn Mar 31 '20 at 21:44
  • I would be useful if you show the full code, where you call the `Temperaturanzeige` object and call the `temperaturEingeben()` function that gives you the `NullPointerException`. – mastropi Mar 31 '20 at 21:48
  • @JohannesKuhn There is probably a dupe but that one is too generic to be of use. I scanned the topmost 3 answers and those didn't contain the issue. – Maarten Bodewes Mar 31 '20 at 21:48
  • Then close if for small error. – Johannes Kuhn Mar 31 '20 at 21:50

2 Answers2

4
int[] temperatur=new int[24];

Creates a new variable, remove the int[].

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
sinclair
  • 2,812
  • 4
  • 24
  • 53
0

You create a new variable in the constructor instead of assign a variable. Change this:

int[] temperatur=new int[24];  

to this:

this.temperatur = new int[24];  
sinclair
  • 2,812
  • 4
  • 24
  • 53
Jerome Wolff
  • 356
  • 3
  • 19