2016-11-28 57 views
-1

我已经定义了一个对象,然后从文件扫描器创建了大量对象。我已经通过一个while循环将这些对象添加到ArrayList中以存储它们以备后用。Java - 从阵列列表中打印对象

我现在试图打印出所说的对象作为字符串,我发现的问题是它有各种属性(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

您可以在RoomoverridetoString()方法和写入格式化输出中实现,例如:

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.printlnRoom对象,它将打印输出。

+0

@downvoter downvote的任何理由? –

+0

使用'StringBuilder'时,使用'append'方法而不是'+'。 –

+0

@ W-S更新了答案。 –