Skip to content
Advertisement

Initialize an array of multiple class objects in java?

I need to use a constructor to initialize an array of class objects, but I can’t figure out the syntax to make it work. I need to include one String and five ints. Here are some neccessary details from my code.

public Event(String n, int g)
   {
      eventNumber=n;
      guests=g;
   }

From “Event.java”

public DinnerEvent(String number, int guests, int entree, int sideOne, int sideTwo, int dessert)
   {
      super(number, guests);
      entreeID=entree;
      sideOneID=sideOne;
      sideTwoID=sideTwo;
      dessertID=dessert;
   }

From “DinnerEvent.java”, which extends Event.java.

for(int x=0; x<EVENTS_QUANTITY; ++x)
      {
         String n;
         int g, e, s1, s2, d;
         Scanner input=new Scanner(System.in);
         System.out.print("Enter event number, number of guests, and ID of entree, two sides, and a dessert.");
         nums[x]=input.nextLine();
         ints[x][0]=input.nextInt();
         ints[x][1]=input.nextInt();
         ints[x][2]=input.nextInt();
         ints[x][3]=input.nextInt();
         ints[x][4]=input.nextInt();
      }
      
      DinnerEvent[][] events={ {nums[0], ints[0][0], ints[0][1], ints[0][2], ints[0][3], ints[0][4]},
                           {nums[1], ints[1][0], ints[1][1], ints[1][2], ints[1][3], ints[1][4]},
                           {nums[2], ints[2][0], ints[2][1], ints[2][2], ints[2][3], ints[2][4]},
                           {nums[3], ints[3][0], ints[3][1], ints[3][2], ints[3][3], ints[3][4]}};

From “DinnerEventDemo.java”. Code here is very messy because I was just trying different things to get it to work. So far, no luck. Instructions specifically request this be done using an array of DinnerEvent objects and through using the constructor in DinnerEvent.java. I can send more surrounding code if necessary. If a variable is not declared in these excerpts, it’s declared beforehand.
This is my first time posting here, so I apologize if my formatting is off or I don’t follow the typical posting etiquette on this site. Help is appreciated.

Advertisement

Answer

Assuming the scanner values as the parameters of constructor, you can do something like this

DinnerEvent[] events = new DinnerEvent[EVENTS_QUANTITY];
for(int x=0; x<EVENTS_QUANTITY; ++x)
      {
         String n;
         int g, e, s1, s2, d;
         Scanner input=new Scanner(System.in);
         System.out.print("Enter event number, number of guests, and ID of entree, two sides, and a dessert.");
         n=input.nextLine();
         g=input.nextInt();
         e=input.nextInt();
         s1=input.nextInt();
         s2=input.nextInt();
         d=input.nextInt();

         events[x] = new DinnerEvent(n, g, e, s1, s2, d);
      }

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement