gpt4 book ai didi

类中带有票证的 Java 数组列表

转载 作者:行者123 更新时间:2023-11-30 02:34:28 25 4
gpt4 key购买 nike

我必须在java中实现Ticket类。这是我的代码:

public class Ticket {

private String name;
private Float defaultPrice;
private Event event;
private static ArrayList<Ticket> ticketList;

public Ticket(String name, Float defaultPrice) {
this.name = name;
this.defaultPrice = defaultPrice;
}

public ArrayList<Ticket> getAllTickets() {
return ticketList;
}

我的主要问题是如何创建 Ticket 类的实例,ticketList 具有新创建的 Ticket 对象。因为稍后我必须使用 public getAllTickets() 方法来获取所有门票。提前致谢!

最佳答案

完整示例:

    package stackoverflow;

import java.math.BigDecimal;

public class Ticket {

private String name;
private BigDecimal defaultPrice;

public Ticket(String name, BigDecimal defaultPrice) {
this.name = name;
this.defaultPrice = defaultPrice;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name =

name;
}

public BigDecimal getDefaultPrice() {
return defaultPrice;
}

public void setDefaultPrice(BigDecimal defaultPrice) {
this.defaultPrice = defaultPrice;
}
}

事件类别:

package stackoverflow;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Event {

private Date date;
private List<Ticket> ticketList;

public Event(Date date) {
this.date = date;
this.ticketList = new ArrayList<>();
}

public void addTicket(Ticket ticket) {
this.ticketList.add(ticket);
}

public List<Ticket> getTicketList() {
return this.ticketList;
}
}

主类:

package stackoverflow;


import java.math.BigDecimal;
import java.util.Date;

public class Main {

public static void main(String[] args) {
Event eventX = new Event(new Date());

eventX.addTicket(new Ticket("ticket1", new BigDecimal(50)));
eventX.addTicket(new Ticket("ticket2", new BigDecimal(50)));
eventX.addTicket(new Ticket("ticket3", new BigDecimal(50)));
eventX.addTicket(new Ticket("ticketPremium", new BigDecimal(100)));

for (Ticket ticket: eventX.getTicketList()) {
System.out.println("name:" + ticket.getName() + " price: " + ticket.getDefaultPrice());
}

}
}

关于类中带有票证的 Java 数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43457642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com