1

Compiler issues: NullPointerException in the line "mass[i].mainN = scan.nextInt();". To my mind, I've inizialized all variables "mainN" and the array "mass". What can be the reason of the exception?

import java.util.Scanner;

public class Robotics{

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    int N = scan.nextInt();
    Robo[] mass = new Robo[N];
    for(int i = 0; i < mass.length; i++) {
        mass[i].mainN = scan.nextInt();
        mass[i].auxiliary = scan.nextInt();
    }
    scan.close();
}

class Robo{
    int mainN;
    int auxiliary;
}
BigButovskyi
  • 109
  • 1
  • 9

1 Answers1

1

Initializing the array is not sufficient, you must also initialize each individual element:

Robo[] mass = new Robo[N];
for(int i = 0; i < mass.length; i++) {
    mass[i]= new Robo(); // Add this line
    mass[i].mainN = scan.nextInt();
    mass[i].auxiliary = scan.nextInt();
}

Java allocated an array of null elements. This is not particularly intuitive, especially to programmers with prior exposure to C++.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523