我有點難倒在這裏。使用嵌套for循環的布爾多維數組 - 使它停止
我對Java /編程相對較新。我想製作一個4x4格子的「書籍座位」計劃。這個多維數組的類型是布爾類型,所以如果座位沒有被佔用,它將返回false,但是如果它被使用,它將返回true。我希望能夠指定不同的座位,因此前兩行將與最後兩行不同。現在我有一個方法,但只要我調用該方法,它就會記錄整個前兩行(從邏輯上講,它應該是這樣)。但是我只想一次只能預訂一個座位,這樣一旦預訂了一個座位,它就會結束這個循環。如果我選擇我想預訂另一個座位,它將移動到那些行或列中的下一個可用座位。
這裏是到目前爲止的代碼:
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("");
}
}
}
}
完美的是,這是做的伎倆! – 2012-02-10 20:57:41
此外,您可能想使用'!seating [row] [col]'而不是'seating [row] [col] == false'。 – 2012-02-10 21:12:54