Java Classes

In your main method, make an array of type Person Fill it with Person objects of the following people and then print the names of each from that array. Each person should be on their own line formatted as shown below. Fred, 24 Sally, 26 Billy, 15 Here is what I got so far but its throwing an error: class Main { public static Person[] people; public static void main(String[] args) { people[0] = new Person("Fred", 24); people[1] = new Person("Sally", 26); people[2] = new Person("Billy", 15); for(int i = 0; i < people.length; ++i){ System.out.println(people[i].name + people[i].age); } } } public class Person{ public String name; public int age; public Person(String name, int age){ this.name = name; this.age = age; } public String getName(){ return name; } public void setName(String name){ this.name = name; } public int getAge(){ return age; } public void setAge(int age){ this.age = age; } }

4/9/2019 9:41:21 PM

Albert Yakubov

6 Answers

New Answer


Since you currently work with classes, I would recommend you to deepen this topic once. * constructor overloading * method overwriting/overloading * the oop stuff (encapsulation, polymorphism, inheritance, abstraction)


public static Person[] people = new Person[3]; If you want to create an array you have to set the size. For example: int[] numbers = new int[10] --> an int array with length = 10; Or: int[] = {1,3,4} --> an int array with variables (length = 3)


If I am right, D_Stark mentioned it. If you have setters and getters --> make your variables private and use this methods. System.out.println(people[i].getName + ", " + people[i].getAge);


you were right on the size of the array, after i indicated that, it worked. thank you so much for all ypur help. while you are still on here, what should I study next to be better prepared for full stack development


Maybe this is helpful for you: https://www.quora.com/I-want-to-become-a-full-stack-Java-developer-How-should-I-proceed


Here is a little different approach using an ArrayList. public class People { public class Personal { String name; int age; } java.util.ArrayList<Personal>() person = new java.util.ArrayList<>(); public People() { } public People(String name, int age){ this.name=name; this.age=age; } public static void main(String[ ] Args) { person.add(new Personal("Fred",24)); person.add(new Personal("Sally",26)); person.add(new Personal("Billy",15)); // you may add as many as you like for (int j=0; j<person.size(); j++) { System.out.println(person.get(j).name+" is "+person.get(j).age+" years old."); } }