本窗口售票系统实现了三个售票窗口的随机售票,实现随机到某一个窗口买票,总票余量都会减少,即三个窗口共享同一个票余量。若票余量小于一次性购票量,则提示报错;若车票售罄,则代码结束运行。
代码实现:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Random;
public class Main {
//首先设置总票量
public static int totalTickets = 100;
public static void main(String[] args) {
List<TicketOffice> list = new ArrayList<>();
TicketOffice t1 = new TicketOffice("SC01", "1号负责人", "1号位");
TicketOffice t2 = new TicketOffice("SC02", "2号负责人", "2号位");
TicketOffice t3 = new TicketOffice("SC03", "3号负责人", "3号位");
list.add(t1);
list.add(t2);
list.add(t3);
Scanner sc = new Scanner(System.in);
while (totalTickets > 0) {
System.out.println("请输入你要购票的数量:");
int num = sc.nextInt();
// 检查输入的车票数量是否有效
if (num <= 0) {
System.out.println("请输入有效的车票数量!");
continue;
}
// 随机选择一个售票窗口
Random random = new Random();
int randomIndex = random.nextInt(list.size());
TicketOffice selectedOffice = list.get(randomIndex);
try {
selectedOffice.saleTicket(num);
//totalTickets -= num; // 更新剩余车票总数
System.out.println("成功从 "+selectedOffice.getOfficeId()+" 窗口售出 "+num+" 张车票。剩余车票:"+totalTickets);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
System.out.println("所有车票已售罄!");
sc.close();
}
}
class TicketOffice {
private String officeId;
private String administor;
private String address;
public TicketOffice() {}
public TicketOffice(String officeId, String administor, String address) {
this.officeId = officeId;
this.administor = administor;
this.address = address;
}
public void saleTicket(int ticketNum) throws Exception {
if (Main.totalTickets >= ticketNum) {
Main.totalTickets -= ticketNum;
System.out.println("售出 " + ticketNum + " 张车票。");
} else {
throw new Exception("票余量不足!");
}
}
public String getOfficeId() {
return officeId;
}
}
部分运行结果: