我正在尝试创建一个名为isAvailable的布尔方法,该方法接受航班上的座位号作为参数,返回一个指示该座位是否可用的布尔值。使用类似于井字游戏程序的代码,该代码将把20这样的座位号转换为二维数组的行和列索引。如果航班上有任何可用座位,则返回true。
public class Flight {
/*
* declare instance variables
* each flight object that is created will have its own copy of these
* These are declared as private to ensure that external Java code
* cannot access them directly and assign any arbitrary values to them.
*/
String flightNumber;
int rows;
int seatsPerRow;
boolean [][] seat;
double fare;
String origin;
String destination;
/*
* The constructor
* Contains code that initially sets up each flight object when it is
* first created. Always has the same name as the class.
*/
public Flight (String flightNumber, int rows, int seatsPerRow, double fare, String origin, String destination) {
//call the mutator methods and let them initialize the instance variables
setflightNumber(flightNumber);
setRows(rows);
setSeatsPerRow(seatsPerRow);
setFare(fare);
setOrigin(origin);
setDestination(destination);
seat = new boolean [rows][seatsPerRow]
for(int i = rows, int x = seatsPerRow; i>0, x>0; i--, x--){
seat[i][x] = true;
}
}//end of constructor
/*
* The accessor methods
* These report the current values of the Flight object's instance variables
*/
public String getFlightNumber() {
return flightNumber;
}
public int getRows() {
return rows;
}
public int getSeatsPerRow() {
return seatPerRow;
}
public double getFare() {
return fare;
}
public String getOrigin() {
return origin;
}
public String getDestination() {
return destination;
}
public boolean isAvailable(int userRow, int userSeatPerRow) {
int row = 0;
int seatPerRow = 0;
}
}//end of accessors
这就是您想要的吗?
public boolean isAvailable(int userRow, int userSeatPerRow) {
return !seat[userRow][userSeatPerRow];
}
这假设seat[x][y]
阵列是真的,如果座位在x排,位置y被占用
如果座位被占用,则seat[userRow][userSeatPerRow]
为true
。
当!
时,我们得到了反转的逻辑,所以true
变成了false
。
因此,函数返回false
是座位被占用,因为那时它不可用。如果座位是空的,情况正好相反。然后函数返回true
要找到第一个可用的座位,你可以这样做:
for (int row = 0; row < getRows(); row++) {
for (int column = 0; column < getSeatsPerRow(); column++) {
if (isAvailable(row, column)) {
System.out.println("Sear " + row +", " + column + " is emply!!!!!!");
}
}
}
检查是否有可用座位
public boolean areThereAnyAvailableSeats() {
for (int row = 0; row < getRows(); row++) {
for (int column = 0; column < getSeatsPerRow(); column++) {
if (!seat[userRow][userSeatPerRow]) {
return true;
}
}
}
return false;
}
您的函数
public boolean isAvailable(int userRow, int userSeatPerRow) {
int row = 0;
int seatPerRow = 0;
}
不返回任何内容。是因为你不知道该放什么,还是忘记了。。。?
大概,您会想要一个将seat设置为false的"book"方法(在seat[][]数组中切换一点);isAvailable
方法需要访问数组并返回值
return seat[userRow][userSeatPerRow].
在您的方法中将row
和seatPerRow
设置为零,而这些都是传入的参数,这让我感到困惑。