要实现Java软件的退票功能,首先需要有一个票务系统来管理票的信息和状态。下面是一个简单的代码示例,展示如何使用Java编写退票功能。
首先,我们需要定义一个Ticket类来表示一张票,其中包含票的信息和状态:
public class Ticket {
private int ticketId;
private String passengerName;
private boolean isRefunded;
public Ticket(int ticketId, String passengerName) {
this.ticketId = ticketId;
this.passengerName = passengerName;
this.isRefunded = false;
}
public int getTicketId() {
return ticketId;
}
public String getPassengerName() {
return passengerName;
}
public boolean isRefunded() {
return isRefunded;
}
public void refund() {
if (!isRefunded) {
isRefunded = true;
System.out.println("Ticket " + ticketId + " has been refunded for passenger " + passengerName);
} else {
System.out.println("Ticket " + ticketId + " has already been refunded");
}
}
}
在这个示例中,我们使用ticketId
来标识一张票,passengerName
表示乘客姓名,isRefunded
表示票是否已退票。refund()
方法用于执行退票操作,并输出相应的信息。
接下来,我们需要一个TicketSystem类来管理票务系统的功能,包括购票和退票:
import java.util.ArrayList;
import java.util.List;
public class TicketSystem {
private List<Ticket> tickets;
public TicketSystem() {
tickets = new ArrayList<>();
}
public void purchaseTicket(int ticketId, String passengerName) {
Ticket ticket = new Ticket(ticketId, passengerName);
tickets.add(ticket);
System.out.println("Ticket " + ticketId + " purchased for passenger " + passengerName);
}
public void refundTicket(int ticketId) {
for (Ticket ticket : tickets) {
if (ticket.getTicketId() == ticketId) {
ticket.refund();
return;
}
}
System.out.println("Ticket " + ticketId + " not found");
}
}
在TicketSystem类中,我们使用一个列表来存储所有的票。purchaseTicket()
方法用于购票,创建一个新的Ticket对象并将其添加到列表中。refundTicket()
方法用于退票,遍历列表找到对应的票并调用其refund()方法。
下面是一个简单的主函数来演示使用退票功能:
public class Main {
public static void main(String[] args) {
TicketSystem ticketSystem = new TicketSystem();
// 购票
ticketSystem.purchaseTicket(1, "Alice");
ticketSystem.purchaseTicket(2, "Bob");
ticketSystem.purchaseTicket(3, "Charlie");
// 退票
ticketSystem.refundTicket(2);
ticketSystem.refundTicket(4);
}
}
运行这段代码,输出将是:
Ticket 1 purchased for passenger Alice
Ticket 2 purchased for passenger Bob
Ticket 3 purchased for passenger Charlie
Ticket 2 has been refunded for passenger Bob
Ticket 4 not found
这个代码示例实现了一个简单的Java软件退票功能。当用户购票时,会创建一个Ticket对象并添加到票务系统中,当用户退票时,会根据票号找到对应的票并执行退票操作。
标签:java,passengerName,退票,isRefunded,软件,Ticket,ticketId,public From: https://blog.51cto.com/u_16175491/6785429