+ 4

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; } }

9th Apr 2019, 9:41 PM
Albert Yakubov
Albert Yakubov - avatar
7 Answers
+ 6
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)
9th Apr 2019, 10:58 PM
Denise Roßberg
Denise Roßberg - avatar
+ 4
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);
9th Apr 2019, 10:10 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
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)
9th Apr 2019, 10:03 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
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
9th Apr 2019, 10:22 PM
Albert Yakubov
Albert Yakubov - avatar
9th Apr 2019, 11:03 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
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."); } }
28th Apr 2019, 4:01 AM
Brent Grigsby
Brent Grigsby - avatar
0
12th Oct 2020, 5:28 PM
Krishan kumar
Krishan kumar  - avatar