Exception in thread "main" java.lang.NullPointerException in the row disks [i] = i; when trying to create an object.

import java.util.Arrays; public class Sterzhen { int number; int disksNumber; int disks[]; public Sterzhen(int number, int disksNumber){ this.number = number; this.disksNumber = disksNumber; for (int i=disksNumber;i>=0;i--){ disks[i] = i; } } void print(){ System.out.printf("Sterzhen nomer: %d\nDiskov: %d\nDiski: %s\n",number,disksNumber,Arrays.toString(disks)); } public static void main(String[] args) { Sterzhen st = new Sterzhen(1,5); st.print(); } } 

    1 answer 1

    not when creating an error, but when trying to write a value to cell number i . Only you forgot to initialize it with its size.

    either here

     int disks[]; // int disks[] = new int[ЗНАЧЕНИЕ]; 

    either in the constructor itself. Maybe it should be like this:

     disks = new int[disksNumber]; 

    I don’t know where exactly, but you must initialize it and set a specific size before trying to write something down.

    • disks = new int [disksNumber]; in the constructor before the cycle itself helped - Philipp Ytkin