Search code examples
javaarraylistlinked-listtostring

Print the index of the array in his toString method


Hi all and sorry for my English, I'm not very good at writing.

I am actually programming a booking system for a cinema (it is an University project). I have a LinkedList of Users and inside i put an ArrayList of booked seat. The bookedSeat Class is the following:

public class bookedSeat implements Serializable {

private Hours h;
private Days d;
private int hallNumber;
private int seatNumber;
//getter&setter and constructor below...

When i display the booking of a user i use the toString method:

@Override
public String toString() {

    String ret="\n \033[31m Booking "  +  ": day: " + getD() 
    + ", Hall: " + getH() + ", hour: " + getH() + ", seat number: " + 
    getSeatNumber() + "\n";
    return ret;
} 

I get this output once i book a couple of seat:

User{Nome=Daniele, Booked Seat: [
Booking : Day: 24, Hall: 1, hour: 20, seat number: 45
, 
Booking : Day: 29, Hall: 1, hour: 20, seat number: 24
]} 

I now ask to user which booking he wants to dismiss and i ask him to write the number of booking so i can save this value-1 and remove the related index (1 for the first, 2 for the second etc...).

Is there a chance to get the number of the Booking from the toString method? to be more clear: I want this output from the toString:

User{Nome=Daniele, Booked Seat: [
Booking 1: Day: 24, Hall: 1, hour: 20, seat number: 45
, 
Booking 2: Day: 29, Hall: 1, hour: 20, seat number: 24
]} 

Thanks for any efforts to help!


Solution

  • You need to add the index to the final string in the toString of User, not BookedSeat.

    // User.toString
    @Override
    public String toString() {
        StringBuilder retVal = new StringBuilder("User{" +
                "name='" + name + '\'' +
                ", bookedSeats=[");
        for (int i = 0 ; i < bookedSeats.size() ; i++) {
            retVal.append("Booking ");
            retVal.append(i + 1);
            retVal.append(": ")
            retVal.append(bookedSeats.get(i));
            retVal.append("\n");
        }
        retVal.append("]\n}");
        return retVal.toString();
    
    }
    
    // BookedSeat.toString
    @Override
    public String toString() {
        return "Hours: " + h +
                ", Days: " + d +
                ", Hall Number: " + hallNumber +
                ", Seat Number: " + seatNumber;
    }