Curtis B
Curtis B

Reputation: 39

declaring an Object in another class

so I have the class Person, I then have another class called Building and I'm trying to create an object in building giving the person a default location and adding this into my toString method, so it displays when I run the program:

public class Person {

    private Point p;

    Person(Point np) {
        this.p = np;
    }

    public String toString() {
        return "Person at " + p.getX() + ", " + p.getY();
    }

In the Building class I have declared private Person p then in setBuilding created the object with a new location then added p into my toString method, I think I got the right idea but whenever I run building it displays "null" and not "Person at " with the set X and Y coordinate which is in my person class. So ive definitely gone wrong somewhere any pointers in the right direction would be a great help thank you.

public class Building {
private int xSize = 10;             
private int ySize = 10; // and y
private ArrayList<Room> allRooms;
private Person P;

Building (String first){
allRooms = new ArrayList<Room>(); 
setBuilding(first); 
}

 public void setBuilding(String bS) {
 String[] Space;    

    allRooms.clear(); 
    Space = bS.split(";");  
    //defining the x and y coordinate
    String[] buildingSize = Space[0].split(" "); 
    xSize = Integer.parseInt(buildingSize[0]); 
    ySize =Integer.parseInt(buildingSize[1]); 
    allRooms.add(new Room(Space[1]));
    allRooms.add(new Room(Space[2])); 
    allRooms.add(new Room(Space[3])); 
    Person P = new Person (new Point(2,3));
 }


public String toString() {
     String s = "Building size " + xSize +","+ySize + P + '\n'; 
    for (Room r : allRooms) { //for loop 
        s += r.toString();
    }

    return s;  
}



public static void main(String[] args) {
    // TODO Auto-generated method stub
    Building b = new Building("11 11;0 0 5 5 3 5;6 0 10 10 6 6;0 5 5 10 2 5");  // create 
    System.out.println(b.toString());               // and print

}

}

Upvotes: 1

Views: 65

Answers (1)

janardhan sharma
janardhan sharma

Reputation: 335

Please follow the java naming conventions.

private Person person; 

is the correct naming convention.

Now in your setBuilding method,

public void setBuilding(String bS) {
 .
 .
this.person = new Person (new Point(2,3));

}

this will do.

Hope this helps. Cheers !!!

Upvotes: 1

Related Questions