So I get more or less how arrays work, and I made them work in simple programs with numbers and what not.
But now I wanna get more complex and say I want to make a small (fleeting) database of people, so I wrote a class for it...
public class Person { public static int count; private int id; // define variables for each object private String name; private String surname; private int age; private int weight; public Person() { // set the id equal to the total class count this.id = count; // increase the count count++; } public void setName(String name) { this.name = name; } public void setSurname(String surname) { this.surname = surname; } public void setAge(int age) { this.age = age; } public void setWeight(int weight) { this.weight = weight; } public int getId() { return id; } public String getName() { return name; } public String getSurname() { return surname; } public int getAge() { return age; } public int getWeight() { return weight; } }
I'm assuming the class is fine and that I'm doing something wrong as far as scanning the people into the array...
Please don't mind the crude programming, I've only been learning for a week.
import java.util.Scanner; public class Application { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Amount of people?"); int n = scan.nextInt(); Person[] people = new Person[n]; int x = n; for (int i=0 ; i < x ; i++ ) { System.out.println("Insert Person number " + (i+1) ); String name = scan.nextLine(); people[i].setName(name); } for (int i=0 ; i < x ; i++ ) { System.out.print(people[i].getName() + " "); } } }
I'm getting
"Amount of people?
2
Insert Person number 1
Exception in thread "main" java.lang.NullPointerException
at Application.main(Application.java:34)"
Of course this line is total garbage:
people[i].setName(name);
What am I doing wrong?