0

I'm learning array of record and exercising with a problem. However I got this error response

Exception in thread "main" java.lang.NullPointerException

and this is my code

import java.util.Scanner;

public class Employees {

public static Scanner sc = new Scanner(System.in);
int n;
int id, salary;
String name, group;

Employees[] employees = new Employees[100];

void initializing_array(){
    System.out.print("Number of Data: ");
    n = sc.nextInt();

    if( n >= 0 && n <= 100){
        for(int i=0; i <= n; i++){
            System.out.print("ID: ");
            employees[i].id = sc.nextInt();
            System.out.print("Name: ");
            employees[i].name = sc.nextLine();
            System.out.print("Group: ");
            employees[i].group = sc.nextLine();
            System.out.print("Salary: ");
            employees[i].salary = sc.nextInt();


        }
    }else{
        System.out.println("==========");
    }
}

void output_array(){
    for(int i=0; i < n; i++){
            System.out.println("ID: "+employees[i].id);
            System.out.println("Name: "+employees[i].name);
            System.out.println("Group: "+employees[i].group);
            System.out.println("Salary: "+employees[i].salary);

    }
}

public static void main(String[] args) {
    Employees emp = new Employees();

    emp.initializing_array();
    emp.output_array();
}

}

The error was on looping in initializing_array() when I typed some data. Thanks in advance.

nasoph
  • 9
  • 2

1 Answers1

1

Every NullPointerException is a duplicate. It means you did not initialize an object.

There are two problems in this code.

  1. The if( n >= 0 && n <= 100){ is wrong, since an n of 100 will throw an IndexOutOfBoundsException.

  2. Though the Employees[] array is allocated, no Employee object is ever created. (wrong loop counter as well).

(note: not sure why the code formatting is not working)

for (int i = 0; i < n; ++i) {  
  employees[i] = new Employee();  //<-- ADD THIS LINE  
  System.out.print("ID: ");  
  employees[i].id = sc.nextInt();  
  System.out.print("Name: ");  
  ...  
}
KevinO
  • 4,303
  • 4
  • 27
  • 36