-1

I have a class called Seat as follows:

public class Seat {
    private String seatType; // E for economy, B for business class
    private boolean Available; // false:booked, true:available

    public Seat (String seatType, boolean Available) {
        this.seatType = seatType;
        this.Available = Available;
    }
    public boolean getAvailability() {
        return Available;
    }
    public String getSeatType() {
        return seatType;
    }
}

I would like to create an array called Seats with 10 elements where each of the elements is of type Seat as in the class above. I would like to initialize it with an assignment statement where each element is false for the seatType and 'E' as the seat type.

Can someone provide me with the assignment statement that will accomplish this?

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
Wayne Hann
  • 11
  • 1
  • 3
  • 3
    What have you tried so far? Please provide us with your attempt to solve the problem. We are not here to do the work for you. – Ben Mar 01 '18 at 10:18
  • you'll need more than one statement. First, you'll need to create the array, then you'll need to initialize every element. – Stultuske Mar 01 '18 at 10:19
  • 1
    you also might want to provide setters, and read up on naming conventions – Stultuske Mar 01 '18 at 10:20
  • I have tried various things like 'Seat [] Seats = {false,"E")' and various combinations like that but no luck – Wayne Hann Mar 01 '18 at 10:20
  • 1
    @Stultuske You can do it in one with a generated limited stream and an array collector. – daniu Mar 01 '18 at 10:21
  • 1
    1) How do you create an array? 2) How do you create an instance of `Seat` with the required properties? 3) How do you assign a value to an array element? Put them together with a loop. – Andy Turner Mar 01 '18 at 10:23

3 Answers3

0

First of all, you should create your 'initial' Seat:

public class Seat
{
  public static final DEFAULT_SEAT = new Seat("E", false);
  ...
}

Then, create your array with these seats:

List<Seat> seats;
int        counter;
seats = new ArrayList<Seat>();
for (counter = 0; counter < 10; counter++)
  seats.add(Seat.DEFAULT_SEAT);

Which, of course, can also be created like this:

Seat[] seats;
int    counter;
seats = new Seat[10];
for (counter = 0; counter < seats.length; counter++)
  seats[counter] = Seat.DEFAULT_SEAT;

If you want separate instances for each element in the array, you could also simply do this (without defining the Seat.DEFAULT_SEAT:

seats[counter] = new Seat("E", false);
Robert Kock
  • 5,795
  • 1
  • 12
  • 20
0

Here's how you create an array and fill it with instances:

// array size
int n = 10;

// create array
Seat[] list = new Seat[n];

// fill
for (int i = 0; i < n; i++) {
    list[i] = new Seat("E",false);
}
Boris Schegolev
  • 3,601
  • 5
  • 21
  • 34
xMilos
  • 1,519
  • 4
  • 21
  • 36
-2

Take a look at Arrays.Fill(Object[] a, Object val) for example

uzilan
  • 2,554
  • 2
  • 31
  • 46