logotransparent.png

Legion of Learners

www.lol-101.com

  • Home

  • Classrooms

  • Courses

  • About Us

    • Executive Team
    • Board Members
  • Resources

  • More

    Use tab to navigate through the menu items.
    To see this working, head to your live site.
    • Categories
    • All Posts
    • My Posts
    sfolax6776
    Oct 28, 2019
      ·  Edited: Dec 03, 2021

    4.2 How to create arrays of objects?

    in AP Computer Science A

    A. Introduction

    Now you are well equipped with the skills to create an array of 300 students, - not only their height or weight, but ALL info of these students. You define what you'd like to include in class Students, and then create an array of 300 Student objects. Each object may have a student's name, birthday, height, weight, gpa...

    B. Watch (slides)

    C. HW

    1) Use class Person below to create an array of 5 persons by calling the constructor in main().

    2) Call the setAge() method to update everyone's age, then print out all 5 persons using an enhanced for loop.

    3) Create a 2-D array of Person to store 3 age groups: <12 years old, 12-18 years old, >18 years old. i.e. The first row has 5 persons who are <12 years old, the second row has 5 persons who are 12-18, and the third row has 5 persons who are >18 years old. Use an enhanced for loop to print out all 15 persons.

    public class Person {
    	private String name;
    	private int age;
    	public Person(String aName, int anAge)
    	{
    		name = aName;
    		age = anAge;
    	}
    	
    	/* @return the String form of this person /
    	public String toString()
    	{ 
    		return name + " " + age; 
    	}
    	
    	public void printPerson()
    	{ 
    		System.out.println(this); 
    	}	
    	public void setName(String newName) {
    		name = newName;
    	}
    	
    	public void setAge(int newAge) {
    		age = newAge;
    	}
    
    }

    0 comments
    0
    0 comments

    Questions? Email us at legionoflearners@gmail.com or join our WeChat group!

    • lol-101dotcom

    ©2020 Legion of Learners