I’m kind of stumped here.
I’m relatively new to Java/Programming in general. I want to make a program that “books seats” in a 4×4 grid. This multidimensional array will be of the type boolean so that if the seat is not taken, it returns false, but if it is taken it will return true. I want to be able to specify different seats, so like the first two rows will be a different section than the last two rows. Right now I have a method but it just books the entire first two rows as soon as I call that method (as it should, logically speaking). But I want to only be able to book one seat at a time, so that it will end that for loop as soon as one seat is booked. If I select that I want to book another seat, it will move to the next available seat in those rows or columns.
Here is the code so far:
import javax.swing.JOptionPane;
public class Seats{
int maxRows = 4;
int maxCols = 4;
boolean seating[][] = new boolean[maxRows][maxCols];
String bookSeat = null;
public static void main(String []args){
Seats seats = new Seats();
seats.start();
}
public void start(){
bookSeat = JOptionPane.showInputDialog(null, "Book a seat? (y/n)");
if(bookSeat.equals("y")){
bookSeat();
}else{
JOptionPane.showMessageDialog(null, "Okay.");
}
displaySeats(seating);
}
private boolean bookSeat(){
boolean isBooked = false;
for(int row = 0; row <2; row++){
for(int col = 0;col<maxCols;col++){
if (seating[row][col] == false){
seating[row][col] = true;
isBooked = true;
}
}
}
return isBooked;
}
private void displaySeats(boolean[][] anArray){
String seatTaken;
int r=0;
int c=0;
for(int display=0; display<1; display++){
for(r=0;r<anArray.length;r++){
for(c=0;c<anArray.length;c++){
if (seating[r][c]==false){
seatTaken = "O";
}
else{
seatTaken = "X";
}
System.out.print("\t[" + seatTaken + "] \t");
}
System.out.println("");
}
}
}
}
I think what you’re looking to do is return once you find an open seat and book it — as shown in the method above. This way the loops won’t continue once you book a seat.