I'm writing a program and I want to shorten the code through list comprehension (like those in Python). However, I faced syntax errors while trying to simplify the code:
I've attempted to troubleshoot this problem multiple times, but all the solutions they proposed are through ArrayLists while I want to complete this task in the form of an integer array (int[]).
boolean[][] seats;
Theater(int row, int col) {
for (int i=0; i<row; i++) for (int j=0; j<col; j++) seats[i][j] = false;
}
public int[] findSeats(int row) {
int[] arr = [x for (boolean x : this.seats[row]) if (x == false)];
return arr;
}
I expected the code above to work but the following messages showed up instead:
Syntax error on tokens, delete these tokens
Syntax error on token "]", delete this token
Can anyone please help? Much appreciated.
This language construct of Python is not available in Java. I assume you are finding vacant seats in a row? The closest I thought will be something like this
public int[] findSeats(int row) {
final int[] avSeats = new int[seats[row].length];
IntStream.range(0, seats[row].length).filter(seatNo -> !seats[row][seatNo]).forEach(seatNo -> avSeats[seatNo] = 1);
return avSeats;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.