gpt4 book ai didi

java - 在另一个类中声明一个对象

转载 作者:行者123 更新时间:2023-11-30 05:56:07 25 4
gpt4 key购买 nike

所以我有类Person,然后我有另一个名为Building的类,我试图在建筑物中创建一个对象,为该人提供默认位置并添加这进入我的 toString 方法,因此当我运行程序时它会显示:

public class Person {

private Point p;

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

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

Building类中,我声明了private Person p,然后在setBuilding中创建了具有新位置的对象,然后添加了p 到我的 toString 方法中,我认为我的想法是正确的,但是每当我运行构建时,它都会显示“null”而不是“Person at”,其中设置的 X 和 Y 坐标位于我的人类。所以我肯定在某个地方出错了,任何正确方向的指针都会有很大的帮助,谢谢。

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

}

}

最佳答案

请遵循java命名约定。

private Person person; 

是正确的命名约定。

现在在您的 setBuilding 方法中,

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

}

这样就可以了。

希望这有帮助。干杯!!!

关于java - 在另一个类中声明一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53140826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com