以下是一个简单的Java方法,用于售卖飞机票的示例:
public class FlightTicket { private String destination; private int price; private int numberOfSeats; // 构造函数 public FlightTicket(String destination, int price, int numberOfSeats) { this.destination = destination; this.price = price; this.numberOfSeats = numberOfSeats; } // 获取目的地 public String getDestination() { return destination; } // 获取价格 public int getPrice() { return price; } // 获取可用座位数 public int getNumberOfSeats() { return numberOfSeats; } // 购买机票 public void purchaseTicket(int numberOfTickets) { if (numberOfSeats >= numberOfTickets) { numberOfSeats -= numberOfTickets; System.out.println("成功购买 " + numberOfTickets + " 张 " + destination + " 的机票。"); } else { System.out.println(destination + " 的机票不足,购买失败。"); } } }
在这个示例中,FlightTicket类具有destination、price和numberOfSeats等属性,并且有一个构造函数和一些访问这些属性的方法。
FlightTicket
destination
price
numberOfSeats
purchaseTicket()方法用于购买机票,需要传入购买的机票数量。如果可用座位数大于等于购买数量,则扣除座位数,并输出成功购买的信息。否则,输出购买失败的信息。
purchaseTicket()
可以在FlightTicket类中添加一个静态成员变量来跟踪所有已创建的机票数量:
public class FlightTicket { // 其他代码... private static int numberOfTicketsSold; // 构造函数 public FlightTicket(String destination, int price, int numberOfSeats) { this.destination = destination; this.price = price; this.numberOfSeats = numberOfSeats; numberOfTicketsSold = 0; } // 获取已售出的机票数量 public static int getNumberOfTicketsSold() { return numberOfTicketsSold; } // 购买机票 public void purchaseTicket(int numberOfTickets) { if (numberOfSeats >= numberOfTickets) { numberOfSeats -= numberOfTickets; numberOfTicketsSold += numberOfTickets; System.out.println("成功购买 " + numberOfTickets + " 张 " + destination + " 的机票。"); } else { System.out.println(destination + " 的机票不足,购买失败。"); } } }
现在,可以在类外部访问FlightTicket.getNumberOfTicketsSold()方法,以获取所有已售出的机票数量。
FlightTicket.getNumberOfTicketsSold()
下面是一个示例程序,用于创建两个FlightTicket对象,并分别售出其中一些机票:
public class FlightTicketMain { public static void main(String[] args) { FlightTicket ticket1 = new FlightTicket("北京", 1000, 50); FlightTicket ticket2 = new FlightTicket("上海", 800, 30); ticket1.purchaseTicket(10); ticket2.purchaseTicket(5); System.out.println("已售出 " + FlightTicket.getNumberOfTicketsSold() + " 张机票。"); } }
该程序将输出以下内容:
成功购买 10 张 北京 的机票。 成功购买 5 张 上海 的机票。 已售出 15 张机票。
原文链接:codingdict.net