-1

I've defined an object and then created numerous objects from a filescanner. I've done this by having a while loop keep adding these objects into an ArrayList to store them for later use.

I'm now trying to print out said object as a string, the issue I'm finding is it has various attributes (int, string, double, boolean, boolean, boolean).

Below is the object:

    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;
    }

This is the scanner.

            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();
DMck
  • 50
  • 4

1 Answers1

0

You can override the toString() method in your Room class and write the implementation for formatted output, e.g.:

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();
    }
}

Once this it's done, you can call System.out.println with Room object and it will print the output.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102