Introduction to Java Programming Comprehensive Version 10th
Introduction to Java Programming, Comprehensive Version (10th Edition)
Methods And Arrays
CharterAir wants to create a two dimension array to represent the seats on its charter aircraft. Initially, all rows and columns have zeros, representing empty seats. The plane has eight rows of seats and three seats per row.
1. Declare an integer array with 8 rows and 3 columns.
2. Write a nested loop to initialize all elements to 0.
3. Prompt the user to enter a row. Check that this is a valid row.
4. Write a loop that will promt for a row as long as -1 is not entered.
5. Prompt for a particular seat in a row; enter a column to represent the seat. Check that this is a valid column.
6. If there is a 1 in that row, that indicates the seat is taken. Print a message that says \"Please enter a different seat (column) number\".
7. If not, the seat is freem put a zero in that row and column to indicate that serat is taken. Print a message that says, \"reservation made for row and column\".
8. Once a -1 has been entered, print out the values in all rows and columns.
An example array is shown:
Row 0 has seats 1 and 2 occupied. Row 1 has seats 0,1, and 2 occupied. Row 2 has seat 2 occupied, etc.
011
111
001
000
111
111
101
110
Solution
package ctb;
import java.util.Scanner;
public class CharterAir {
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
int[][] seats = new int[8][3];
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[i].length; j++) {
seats[i][j] = 0;
}
}
do {
System.out.print(\"Enter the Row:\");
int row = scanner.nextInt();
if (row == -1)
break;
if (row >= 0 && row <= 7) {
System.out.print(\"Enter the Column:\");
int col = scanner.nextInt();
if (col >= 0 && col <= 2) {
if (seats[row][col] != 1) {
seats[row][col] = 1;
System.out
.println(\"reservation made for row and column\");
} else {
System.out
.println(\"Please enter a different seat number\");
continue;
}
} else {
System.out.println(\"Invalid column\");
continue;
}
} else {
System.out.println(\"Invalid Row\");
continue;
}
} while (true);
for (int i = 0; i < seats.length; i++) {
System.out.print(\"Row \" + i + \" has seats \");
for (int j = 0; j < seats[i].length; j++) {
if (seats[i][j] == 1)
System.out.print(j + \", \");
}
System.out.println(\"Occupied\");
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
OUTPUT:
Enter the Row:1
Enter the Column:1
reservation made for row and column
Enter the Row:1
Enter the Column:1
Please enter a different seat number
Enter the Row:1
Enter the Column:2
reservation made for row and column
Enter the Row:0
Enter the Column:1
reservation made for row and column
Enter the Row:-1
Row 0 has seats 1, Occupied
Row 1 has seats 1, 2, Occupied
Row 2 has seats Occupied
Row 3 has seats Occupied
Row 4 has seats Occupied
Row 5 has seats Occupied
Row 6 has seats Occupied
Row 7 has seats Occupied


