0

我有一种方法可以创建项目并将其添加到 3 个数组列表中,其中 2 个,<String>另一个为<Integer>. 问题是我需要在另一种方法中使用它们(全部 3 个),这将删除我想从它们中删除的项目。

这是“添加”方法:

public static void Hire () throws IOException{
    String name;
    String category,st_wage,st_id;
    int wage,id;

    BufferedReader ob_name = new BufferedReader (new InputStreamReader (System.in));
    BufferedReader ob_category = new BufferedReader (new InputStreamReader (System.in));
    BufferedReader ob_wage = new BufferedReader (new InputStreamReader (System.in));
    BufferedReader ob_id = new BufferedReader (new InputStreamReader (System.in));
    //name on name_list[id]
    //cat. on cat_list[id]
    //wage on wage_list[id]
    System.out.println("Driver Name: ");

    name = ob_name.readLine();

    System.out.println("Driver License: ");
    System.out.println("1 - Motorcycle");
    System.out.println("2 - Van");
    System.out.println("3 - Truck");

    category = ob_category.readLine();

    System.out.println("Wage: ");

    st_wage = ob_wage.readLine();
    wage = Integer.parseInt(st_wage);

    System.out.println("Driver ID: ");

    st_id = ob_id.readLine();
    id = Integer.parseInt(st_id);

    ArrayList<String> name_list = new ArrayList<String>();
    name_list.add(id, name);

    ArrayList<String> cat_list = new ArrayList<String>();
    cat_list.add(id, category);

    ArrayList<Integer> wage_list = new ArrayList<Integer>();
    wage_list.add(id, wage);

    Manage();

}

这是“删除”方法:

public static void Fire (ArrayList<String> name_list, ArrayList<String> cat_list, ArrayList<String> wage_list) throws IOException{
    int id;
    BufferedReader ob_id = new BufferedReader (new InputStreamReader (System.in));
    BufferedReader ob_op = new BufferedReader (new InputStreamReader (System.in));
    //name on name_list[id]
    //cat on cat_list[id]
    //wage on wage_list[id]
    System.out.println("Driver ID: ");

    String st_id = ob_id.readLine();
    id = Integer.parseInt(st_id);

    String name = name_list.get(id);

    System.out.println("Are You Sure to fire Driver "+name+"? (Y/N)");

    char op = (char) ob_op.read();

    if(op == 'Y' || op == 'y'){
        name_list.remove(id);

        cat_list.remove(id);

        wage_list.remove(id);
    }

    Manage();

}
4

1 回答 1

0

在具有自己索引的列表中添加元素时,您将获得 Array Index out of bound 异常。对于您的要求,您所需要的只是一个简单的类

public class Driver {
  public String id ;
  public String name ;
  public String category ;
  public double wage ;

  public Driver(String id, String name) {
    this.id = id;
    this.name =name;
  }  

  // getter and setter methods
}

从用户获取所有输入后创建一个新的 Driver 实例并将其保存在Map

// Key = driverId and value = DriverEntity   
HashMap<String,Driver> map = new HashMap();

此外,您可以使用驱动程序 ID 添加或删除。

于 2013-07-10T05:54:51.710 回答