akacodes121
akacodes121

Reputation: 129

java program bug in eclipse

I am new to java ,I just want to create array of humans object in class Earth

But I am getting error :

Exception in thread "main" java.lang.NullPointerException at Earth.main(Earth.java:14)

I don't know what's wrong with my program it seems everything regarding syntax is correct .

Input:

2

12

aks (...and .. program crash)

    import java.util.*;
public class Human {
    String name;
    int age;
    int height;
    String eyecolor;
    //construct necessary
    public Human() {

    }

    public void speak() {
        System.out.println("Hello My name is " + name);
        System.out.println("I am "+height + "inches tall");
    }
    public void eat() {
        System.out.println("eating...");
    }
}

import java.util.*;
public class Earth {
    public static void main(String args[]) {
        Human humans[] = new Human[10];
        System.out.println("Enter the number of humans\n");

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for(int i=0;i<n;i++) {
            int age;
            String name;
            age = sc.nextInt();
            name = sc.next();
            humans[i].age=age;
            humans[i].name=name;

        }
        for(int i=0;i<n;i++) {
            System.out.printf("name is %s and age is %d \n", humans[i].name,humans[i].age);
        }
            sc.close();
    }
}

Upvotes: 0

Views: 78

Answers (1)

racraman
racraman

Reputation: 5034

Your statement :

Human humans[] = new Human[10];

creates an array to hold 10 humans, but it does not create those humans. Instead, each of the 10 entries is initialised to null - hence your exception when you try to use them in humans[i].age=age;

Instead, create the humans in the loop :

    for(int i=0;i<n;i++) {
        int age;
        String name;
        age = sc.nextInt();
        name = sc.next();
        humans[i] = new Human(); // Add This
        humans[i].age=age;
        humans[i].name=name;
    }

It would also be a good idea to move the declaration of the array to after the user has entered the number of humans they want; As it stands, there's nothing to stop the user entering a number more than 10, which would also cause a problem. So try something like :

    System.out.println("Enter the number of humans\n");

    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    Human humans[] = new Human[n];

Upvotes: 3

Related Questions