0

I'm trying to add data to each item in an array of objects from Scanner input. But I am getting a null pointer exception at patients[i].setPatientId(id).

My code is as follows:

public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        Patient[] patients = new Patient[3];

        for (int i = 0; i < patients.length; i++) {
            System.out.println("Enter a patient Id: ");
            int id = input.nextInt();

            System.out.println("Enter the patient name: ");
            String name = input.next();

            System.out.println("Enter Amount: ");
            double amount = input.nextDouble();

            patients[i].setPatientId(id);
            patients[i].setPatientName(name);
            patients[i].setAmount(amount);
        }
    }

Can someone please tell me what I am doing wrong ?

ExpertGenie
  • 195
  • 3
  • 14
  • 1
    When you create an array of reference type (here Patient type), the array is initially filled with nothing but null values. You cannot use any of the array items until you first create new Patient objects and put them into the array. Think of a reference array like an empty egg carton. You can't make an omelet with the contents of the carton until it is first filled with eggs, and so the first line of your for loop could be `patients[i] = new Patient();` – Hovercraft Full Of Eels Apr 19 '19 at 18:40
  • fixed. thank you bro – ExpertGenie Apr 19 '19 at 18:44

0 Answers0