java实现多人预约座位的程序
时间: 2024-05-10 10:20:03 浏览: 5
以下是一个简单的Java程序,用于实现多人预约座位的功能:
```java
import java.util.*;
public class SeatReservation {
private static int ROWS = 10;
private static int SEATS_PER_ROW = 10;
private static int AVAILABLE_SEATS = ROWS * SEATS_PER_ROW;
private static boolean[][] seats = new boolean[ROWS][SEATS_PER_ROW];
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Welcome to Seat Reservation System!");
System.out.println("Please enter the number of seats you want to reserve (0 to exit):");
int numSeats = scanner.nextInt();
if (numSeats == 0) {
break;
}
if (numSeats > AVAILABLE_SEATS) {
System.out.println("Sorry, there are not enough seats available!");
continue;
}
List<String> reservedSeats = new ArrayList<>();
for (int i = 0; i < numSeats; i++) {
System.out.println("Please enter the row and seat number you want to reserve (e.g. 1A):");
String input = scanner.next();
int row = Integer.parseInt(input.substring(0, 1)) - 1;
int seat = input.charAt(1) - 'A';
if (row < 0 || row >= ROWS || seat < 0 || seat >= SEATS_PER_ROW || seats[row][seat]) {
System.out.println("Sorry, the seat you entered is not available!");
i--;
continue;
}
seats[row][seat] = true;
reservedSeats.add(input);
}
System.out.println("Congratulations! Your seats have been reserved:");
for (String seat : reservedSeats) {
System.out.print(seat + " ");
}
System.out.println();
AVAILABLE_SEATS -= numSeats;
}
System.out.println("Thank you for using Seat Reservation System!");
}
}
```
该程序使用一个二维数组来存储座位的预订情况。当用户输入要预订的座位数量时,程序会逐个询问用户要预订的具体座位,并检查座位是否可用。如果座位已经被预订或者超出了剩余可用座位的数量,程序会提示用户重新输入。如果所有座位都成功预订,程序会输出预订的座位信息,并更新剩余可用座位的数量。用户可以通过输入0来退出程序。