Java - 从arraylist打印对象

时间:2016-11-28 23:31:14

标签: java class oop object arraylist

我已经定义了一个对象,然后从文件扫描器中创建了许多对象。我通过使用while循环继续将这些对象添加到ArrayList中来存储它们以供以后使用。

我现在正在尝试将所述对象打印为字符串,我发现的问题是它有各种属性(int,string,double,boolean,boolean,boolean)。

以下是对象:

    class Room {
    int roomNumber;
    String roomType;
    double roomPrice;
    boolean roomBalcony;
    boolean roomLounge;
    boolean roomReserved;

    public Room(int roomNumber, String roomType, double roomPrice, boolean roomBalcony, boolean roomLounge, boolean roomReserved) {
        this.roomNumber = roomNumber;
        this.roomType = roomType;
        this.roomPrice = roomPrice;
        this.roomBalcony = roomBalcony;
        this.roomLounge = roomLounge;
        this.roomReserved = roomReserved;
    }

这是扫描仪。

            while(file.hasNextLine()){
            int roomNumber = file.nextInt();
            String roomType = file.next();
            double roomPrice = file.nextDouble();
            boolean roomBalcony = file.nextBoolean();
            boolean roomLounge = file.nextBoolean();
            boolean roomReserved = false;
            rooms.add(new Room(roomNumber, roomType, roomPrice, roomBalcony, roomLounge, roomReserved));
            file.nextLine();}
        file.close();

1 个答案:

答案 0 :(得分:0)

您可以在override类中toString() Room方法并编写格式化输出的实现,例如:

public class Room {

    int roomNumber;
    String roomType;

    @Override
    public String toString(){
        StringBuilder builder = new StringBuilder();
        builder.append("Room Number : ").append(roomNumber);
        builder.append("\n");
        builder.append("Room Type : ").append(roomType);
        builder.append("\n");
        return builder.toString();
    }
}

完成此操作后,您可以使用System.out.println对象调用Room,然后打印输出。