java - 引用没有名称的对象时出现问题
问题描述
我是编程新手,我的任务是实现一个简单的巴士票预订系统。
我们应该实现一个使用以下属性添加新公交路线的方法:busNumber
, start
, destination
, price
, currency
。为了保存公交路线,我使用了一个数组列表并保存了这样的新对象:
Booking.add(new Booking(1, "France", "Latvia", 2.05, Currency.EUR))
我现在的问题是使用这些对象,因为它们没有名称。我不知道对象的确切数量,所以我必须这样做(至少我是这么认为的)。发生问题的地方是“删除”方法,即应该删除一条公交路线。我以为我可以使用 Iterator 遍历 ArrayList 并比较busNumber
s 但它不起作用。
我遇到的另一个问题是,当我想打印我的数组列表中的所有对象时,它只打印最后一个对象的次数与我的 ArrayList 中的对象一样多。另外,我的方法和属性现在都是静态的,否则我不知道如何在另一个类中使用它们。
请问有人给新手一些建议吗?
我的代码如下:
import java.util.ArrayList;
import java.util.Iterator;
public class Booking {
static int busNumber;
static int customerID = 1; //First customerID starts with 1
static String name;
static double price;
static int invoiceNumber = 1; //First invoicenumber starts with 1.
static String start;
static String destination;
static Currency currency;
static ArrayList<Booking> bookable = new ArrayList<Booking>();
//Constructor
public Booking(int busNumber, String start, String destination, double price, Currency currency) {
this.busNumber = busNumber;
this.start = start;
this.destination = destination;
this.price = price;
this.currency = currency;
}
public int getBusNumber() {
return busNumber;
}
public static void add(Booking add) { // add-method. Adds the bus routes to the booking system
bookable.add(add);
}
public static void remove(int busNumber) { // Here´s one of my issues. That´s what i have.
Iterator<Booking> it = bookable.iterator();
if ( == busNumber) {
bookable.remove(it);
}
}
public static void listRoute() {
for (Booking element : bookable) {
Terminal.printLine(toString(element));
}
}
public static String toString(Booking element) {
return "000" + busNumber + " " + start + " " + destination + " " + price + " " + currency;
}
}
My second class which is later supposed to be the UI:
public class Input {
public static void main(String[] args) {
Booking.add(new Booking(1, "Mannheim", "Karlsruhe", 2.05, Currency.EUR));
Booking.add(new Booking(2, "Heidelberg", "Karlsruhe", 3.05, Currency.JPY));
Booking.add(new Booking(3, "Germersheim", "Karlsruhe", 4.05, Currency.USD));
Booking.listRoute();
}
}
输出为:“0003, “Germersheim”, “Karlsruhe”, 4.05, Currency.USD” 3 次..
解决方案
推荐阅读
- javascript - 为什么我的 Vis.js 力有向图不在 bootstrap 手风琴的视图中?
- audio - ffmpeg 水平翻转视频
- powerbi - 在 Power BI 中嵌入代码以发布到 Web(公共)时报告未加载
- google-sheets - Google表格,根据包含公式的单元格值添加行
- javascript - 错误:ERR_FAILED (-2) 在关闭和打开新窗口时加载 electronjs
- algorithm - 有障碍物的网格中的最大路径,向右、向左或向下
- jmeter - 使用 jmeter 运行时,我在请求正文中看不到 cookie
- r - 如何从可反应中的单元格呈现按钮触发带有observeEvent的modalBox?
- python - 通过 pip3 安装 cyrptodome 后没有名为 crypto.PublicKey 的模块
- javascript - S3+Cloudfront 与 EC2 部署 React 网站的区别