top of page
Search
Writer's pictureSiah Peih Wee

Using Array to Store Objects in Java

In this article, you will learn to create objects using user defined class and store them in array.

Below is a Cat Class that take in String to define its color. The rest of the attributes are generated by the Constructor. Then it will print out its position and color to the console.

import java.lang.Math;

class Cat {
  int iPosX = 0;
  int iPosY = 0;
  String sColor = "White";

  Cat(String sColor) {
    this.sColor = sColor;
    double dPosX = (Math.random() * 100);
    double dPosY = (Math.random() * 100);

    iPosX = (int) dPosX;
    iPosY = (int) dPosY;

    displayGenerated();
  }

  void displayGenerated()
  {
    System.out.println(this.sColor + " Cat generated to Position X:" + iPosX + " Y:" + iPosY);
  }
}

Next create an Array to store 10 Cats.

Cat[] aCats = new Cat[10];

and a for loop to define each slot in the array to store the generated new Cat.


    for (int i = 0; i < 10; i++) 
    {
      int iColor = (int) (Math.random() * 3);
      
      String sColor = "White";
      switch(iColor)
      {
        case 0:
          sColor = "White";
          break;
        case 1:
          sColor = "Brown";
          break;
        case 2:
          sColor = "Black";
          break;
      }
    
      aCats[i] = new Cat(sColor);
    }

Below is how it will run.


2 views0 comments

Comments


Post: Blog2 Post
bottom of page