让我们从分解代码开始:
public class Cinema { ... }
所以,我们在这里声明一个新的数据类型/数据结构,称为 Cinema。
您要声明的这个数据结构,它有一个名为 seats 的私有属性(您将无法从该 Cinema 类 之外访问它),它是matrix of boolean 类型和一个名为 findAvailable 的公共方法(可以从 Cinema 类外部访问),不需要任何参数。
为了清楚起见,让我们指出任何矩阵都是由一组行组成的,每一行都有它的一组列。此外,我们在 Java 中声明/访问矩阵的方式是:
// Access; telling which columns and rows we want to access.
myMatrix[rowIndex][columnIndex];
// Creation; telling what sizes we want for our matrix.
DataType[][] variable = new DataType[NumberOfRows][NumberOfColumns];
那么让我们分解一下这些座位的代码,好吗?
private boolean[][] seats = {{ true, true, false, false, false, true, true false},
{ true, true, true, true, true, true, true, true},
{ true, true, true, true, true, true, true, true}}
这完全一样:
private boolean[][] seats = {
// This is the instantiation of one row, with 8 columns
{ true, true, false, false, false, true, true false},
// Another row with another 8 more columns (and its values)
{ true, true, true, true, true, true, true, true},
// And another row.
{ true, true, true, true, true, true, true, true}
};
因此,增加一些间距和缩进看起来会更清晰一些;基本上,您正在创建一个布尔矩阵,每行 3 行 8 列。
继续讨论该方法,该方法返回 void,即不返回任何内容。
在该方法中,您正在对矩阵执行简单的搜索:您正在访问每个单元格,以寻找包含“真”值的第一个单元格。
所以让我们通过注释来检查您的代码。
public void findAvailable() {
/* You will use this auxiliar variable to tell or remember if you have found an available spot*/
boolean found = false;
/* This variable is your row indexer, an accumulator that you will use to remember which row to access and how many of them have you accessed at a given time*/
int row = 0;
/*this translates as follows:
WHILE I HAVEN'T FOUND (the free spot) AND I HAVEN'T VISITED EACH ROW OF
SEATS*/
while (!found && row < seats.length) {
/*The same thing, but now it's a column indexer*/
int seat = 0;
/*this translates as follows:
WHILE I HAVEN'T FOUND (the free spot) AND I HAVEN'T VISITED EACH COLUMN
OR/OF SEATS*/
while (!found && seat < seats[row].length) {
// Checking whether the seat at "row, seat" is available
if (seats[row][seat]) {
// If it is, remember it so we can stop looking any further
found = true;
// Notify that you've found an empty seat at "row, column"
System.out.println("Row = " + row + " Seat = " + seat);
}
// Keep looking for seats in the same row
seat++;
}
// If no luck on this row, let's move to another one
row++;
}
// if we've reached this point...
if(!found) System.out.println("There are no seats available this time...");
}