0

Not really sure how to assign objects to the array, help me please

Which class do i do it in?

package Assignment2;

import java.util.Scanner;

import java.io.InputStream;

import java.io.FileNotFoundException;

public class Agent {

   private int NumberOfHouses;

   public static void main(String[] args){
   House test = new House();
   House[] allHouses = new House[10];   
   test.setNumberOfRooms(12);
   System.out.println(test.getNumberOfRooms());
   allHouses[2].setNumberOfRooms(9);
   }

}

package Assignment2;

public class House {

   private int NumberOfRooms = 0, LivingArea, TotalLotArea;
   private Boolean Status; 
   private long Price; 
   static int test;

   public void setNumberOfRooms(int num){
       NumberOfRooms = num;
   }
   public void setLivingArea(int num){
       LivingArea = num;
   }
   public void setTotalLotArea(int num){
       TotalLotArea = num;
   }
       public void setPrice(long num){
       Price = num;
   }
   public int getNumberOfRooms(){
       return NumberOfRooms;
   }    

}

3 Answers 3

1

You can assign Objects to an Array as follows

    House[] allHouses = new House[10];
    for(int i=0;i<allHouses.length;i++) {
        allHouses[i] = new House();
        allHouses[i].setNumberOfRooms(someIntValue);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

hmm i like this, i think im getting somewhere
1

When you do the line House[] allHouses = new House[10];, you are not creating 10 House objects, instead just mentioning that the array allHouses can store references for up to 10 House objects.

So after that you would have to create a new object for each position, set the values and assign it to a location in the array.

Initially, the array would be empty (won't refer to any objects), and you have to put objects into it.

The reason I explained like this and instead of writing just the code, is that you should understand what is going on and not depend on SO for ready baked code :)

5 Comments

you are not creating 10 House objects Yes he is. They are all just null.
@DaftPunk, I think you are contradicting yourself. How is it possible to create 10 House objects and at the same time their value be null.
@DaftPunk null is not an object.
@DaftPunk and silverback are both wrong. It is not 10 House objects, and the array is NOT capable of storing 10 Houses. It is an array that can store 10 reference of House. Of course, that's not 10 House object, you can say there are 10 null reference of House.
@DaftPunk Non sequiturs? What? Where do you see a non sequitur?
0

You can assign objects to an array like this:

allHouses[2] = new House();
allHouses[2].setNumberOfRooms(9);

1 Comment

How do you define allHouses in this case?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.