首页 > 解决方案 > 引用没有名称的对象时出现问题

问题描述

我是编程新手,我的任务是实现一个简单的巴士票预订系统。

我们应该实现一个使用以下属性添加新公交路线的方法:busNumber, start, destination, price, currency。为了保存公交路线,我使用了一个数组列表并保存了这样的新对象:

Booking.add(new Booking(1, "France", "Latvia", 2.05, Currency.EUR))

我现在的问题是使用这些对象,因为它们没有名称。我不知道对象的确切数量,所以我必须这样做(至少我是这么认为的)。发生问题的地方是“删除”方法,即应该删除一条公交路线。我以为我可以使用 Iterator 遍历 ArrayList 并比较busNumbers 但它不起作用。

我遇到的另一个问题是,当我想打印我的数组列表中的所有对象时,它只打印最后一个对象的次数与我的 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 次..

标签: javaarraylist

解决方案


推荐阅读