在Java中设置迭代

时间:2013-07-09 04:51:12

标签: java

我有一间带房间的房子。我递称打电话给这所房子以获得房间,我希望所有房间只打印一次房屋名称。例如HouseName:市政厅 - 其次是每个房间的房间属性。

House house;
Set<House> rooms = house.getRooms();

//Bear in mind that all rooms have the same house name (houseName)
for(House room:rooms){
   System.out.println(room.getHouseName()); // will be the same for all rooms
   System.out.println("Room: "); 
   System.out.println(room.getColor());
   System.out.println(room.getState()); 
   System.out.println();    
}

我想在下面显示的表格中为所有房间输出一次houseName。

Output:
House Name: City Hall
No of Rooms: 3
---------------
Room:
red
old

Room:
blue
damaged

Room:
white
Renovated

1 个答案:

答案 0 :(得分:0)

您可以尝试以下

这是我的Rooms课程

public class Rooms {
String color;
String state;

public String getColor() {
    return color;
}

public void setColor(String color) {
    this.color = color;
}

public String getState() {
    return state;
}

public void setState(String state) {
    this.state = state;
}
}

现在这是我的House Class

public class House {
String houseName;
int numberOfRooms;
Set<Rooms> rooms=new HashSet<>();

public String getHouseName() {
    return houseName;
}

public void setHouseName(String houseName) {
    this.houseName = houseName;
}

public int getNumberOfRooms() {
    return numberOfRooms;
}

public void setNumberOfRooms(int numberOfRooms) {
    this.numberOfRooms = numberOfRooms;
}

public void setRooms(Set<Rooms> rooms) {
    this.rooms = rooms;
}

public Set<Rooms> getRooms() {
    return rooms;
}

public Set<House> getHouse(){
    Set<House> houses=new HashSet<>();
    Set<Rooms> rooms=new HashSet<>();
    House h1=new House();
    Rooms r1=new Rooms();
    Rooms r2=new Rooms();

    r1.setColor("red");
    r1.setState("new");
    r2.setColor("blue");
    r2.setState("old");
    rooms.add(r1);
    rooms.add(r2);
    h1.setHouseName("Haven");
    h1.setNumberOfRooms(2);
    h1.setRooms(rooms);

    houses.add(h1);

    return houses;
}
}

最后这是我的主要课程

public class MyClass {
public static void main(String[] args)  {
   House house=new House();
   Set<House> houses=house.getHouse();
    for(House h:houses){
        System.out.println("House Name: "+h.getHouseName());
        System.out.println("Number of rooms: "+h.getNumberOfRooms());
        for(Rooms r:h.getRooms()){
            System.out.println("Room color: "+r.getColor());
            System.out.println("Room state: "+r.getState());
        }
    }

  }
  }