根据用户输入从 ArrayList 中移除

Remove from ArrayList based on user input

为基础编程课程构建一个非常简单的车辆清单。它需要添加新车辆方法、列出车辆信息方法、删除车辆方法和更新车辆属性方法。

我用 set 和 get 方法建造了一辆汽车 class:

    private String make;
    private String model;
    private String color;
    private int year;
    private int mileage;
    private int index;


    public Automobile(String make, String model, String color, int year,
                      int mileage, int index) {
        this.make = make;
        this.model = model;
        this.color = color;
        this.year = year;
        this.mileage = mileage;
        this.index = index;
    }



    public String getMake() {
        return make;
    }

    public void setMake(String make) {
        this.make = make;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMileage() {
        return mileage;
    }

    public void setMileage(int mileage) {
        this.mileage = mileage;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

}

在我的 Vehicle 中 class 我现在有一个 addVehicle 方法看起来可以工作。

class Vehicle {
    static ArrayList<Automobile> vehicleList = new ArrayList<>();

    public static void addVehicle() {
        Scanner input = new Scanner(System.in);
        System.out.println("## Add Vehicle to Inventory ##");
        System.out.print("Enter Vehicle make: ");
        String make = input.nextLine();
        System.out.print("Enter Vehicle model: ");
        String model = input.nextLine();
        System.out.print("Enter Vehicle color: ");
        String color = input.nextLine();
        System.out.print("Enter Vehicle year: ");
        int year = input.nextInt();
        System.out.print("Enter Vehicle mileage: ");
        int mileage = input.nextInt();
        System.out.print("Enter the Vehicle Index Number: ");
        int index = input.nextInt();
        
        Automobile newCar = new Automobile(make, model, color, year, mileage, index);
        
        vehicleList.add(newCar);
        
        System.out.println("Vehicle Added to Inventory Successfully");

    }

但是,我卡在了我正在尝试构建的 removeVehicle 方法上:

    public void removeVehicle() {
        Scanner input = new Scanner(System.in);
        System.out.println("## Remove Vehicle from Inventory ##");
        System.out.print("Enter the Vehicle Index Number: ");
        int indexRemove = input.nextInt();

        if(    ){
            System.out.println("Vehicle Removed Successfully");
        }
        else{
            System.out.println("No Such Vehicle Exists");
        }

    }

我认为删除车辆的最简单方法是要求用户输入车辆索引号,然后从数组中删除该特定索引号。但我似乎无法取得任何进展,也无法理解从这里何去何从。

public void removeVehicle() {
    Scanner input = new Scanner(System.in);
    System.out.println("## Remove Vehicle from Inventory ##");
    System.out.print("Enter the Vehicle Index Number: ");
    int indexRemove = input.nextInt();

    int oldSize = vehicleList.size();

    for (Automobile vehicle : vehicleList) {
        if (auto.getIndex() == indexRemove) {
            vehicleList.remove(vehicle);
            System.out.println("Vehicle Removed Successfully");
            break;
        }
    }

    if (vehicleList.size() == oldSize) {
        System.out.println("No Such Vehicle Exists");
    }
}

尝试使用 listIterator,因为它将帮助您遍历列表,也将帮助您从列表中删除元素

public static void removeVehicle() {
    Scanner input = new Scanner(System.in);
    System.out.println("## Remove Vehicle from Inventory ##");
    System.out.print("Enter the Vehicle Index Number: ");        
    int indexRemove = input.nextInt();
    ListIterator<Automobile> listIterator = vehicleList.listIterator();
    boolean removed = false;
    while(listIterator.hasNext()) {
        if(listIterator.next().getIndex()==indexRemove) {
            listIterator.remove();
            removed = true;
            break;
        }
    }
    if(removed) {
        System.out.println("Vehicle Removed Successfully");
    }
    else {
        System.out.println("No Such Vehicle Exists");
    }
}

给你!如果您调用过移除车辆方法,我还会显示您列表中的所有车辆。

解决方案 1

我几乎创建了一个 foreach 循环来迭代您现有的列表,并根据提供的索引检查是否存在一个列表。然后它在 if 语句中删除它。如果成功删除它则为 true 否则为 false。

   public void removeVehicle() {
        Scanner input = new Scanner(System.in);
        System.out.println("## Remove Vehicle from Inventory ##");
        
        for(Automobile vehicle : vehicleList){
            System.out.println("make: " + vehicle.make  + "-" + "model: " + vehicle.model + "-" + 
                    "color: " + vehicle.color + "-" + "year: " +  vehicle.year + "-" + 
                    "mileage: " + vehicle.mileage + "-" + "index: " + vehicle.index);
        }
        
        System.out.print("Enter the Vehicle Index Number: ");
        int indexRemove = input.nextInt();
        
        Automobile automobileToBeRemoved = null;
        for(Automobile vehicle : vehicleList){
            if(vehicle.index == indexRemove){
                automobileToBeRemoved = vehicle;
                break;
            }
        }
        
        if(vehicleList.remove(automobileToBeRemoved)){
            System.out.println("Vehicle Removed Successfully");
        }
        else{
            System.out.println("No Such Vehicle Exists");
        }

    }

解决方案 2

      public void removeVehicle() {
        Scanner input = new Scanner(System.in);
        System.out.println("## Remove Vehicle from Inventory ##");

        System.out.print("Enter the Vehicle Index Number: ");
        int indexRemove = input.nextInt();

        boolean removed = false;
        for (Automobile vehicle : vehicleList) {
            if (vehicle.index == indexRemove) {
                removed = vehicleList.remove(vehicle);
                break;
            }
        }

        if (removed) {
            System.out.println("Vehicle Removed Successfully");
        } else {
            System.out.println("No Such Vehicle Exists");
        }

解决方案 3

        public void removeVehicle() {
        Scanner input = new Scanner(System.in);
        System.out.println("## Remove Vehicle from Inventory ##");

        System.out.print("Enter the Vehicle Index Number: ");
        int indexRemove = input.nextInt();

        int originalSize = vehicleList.size();
        vehicleList = vehicleList.stream().filter(vehicle -> vehicle.index != indexRemove)
                .collect(Collectors.toCollection(ArrayList::new));

        if (vehicleList.size() != originalSize) {
            System.out.println("Vehicle Removed Successfully");
        } else {
            System.out.println("No Such Vehicle Exists");
        }
    }

解决方案 4

        public void removeVehicle() {
        Scanner input = new Scanner(System.in);
        System.out.println("## Remove Vehicle from Inventory ##");

        System.out.print("Enter the Vehicle Index Number: ");
        try{
            int indexRemove = input.nextInt();
            int originalSize = vehicleList.size();
            vehicleList = vehicleList.stream().filter(vehicle -> vehicle.index != indexRemove)
                    .collect(Collectors.toCollection(ArrayList::new));

            if (vehicleList.size() != originalSize) {
                System.out.println("Vehicle Removed Successfully");
            } else {
                System.out.println("No Such Vehicle Exists");
            }
        } catch (Exception e){
                System.out.println("No Such Vehicle Exists");
        }
    }

杂项导出:

        public void writeFile() {
        try {
            FileWriter fw = new FileWriter("output.txt");
            for (Automobile vehicle : vehicleList) {
                fw.write("make: " + vehicle.make + "-" + "model: " + vehicle.model + "-" +
                        "color: " + vehicle.color + "-" + "year: " + vehicle.year + "-" +
                        "mileage: " + vehicle.mileage + "-" + "index: " + vehicle.index + "\n");
            }
            fw.close();
            System.out.println("File exported.");
        } catch (IOException e) {
            System.out.println("Error writing file.");
        }
    }

从 Java 8 开始,Collection(因此 List)具有方法 removeIf (Predicate p),该方法允许删除满足应用于每个元素的给定谓词的所有元素集合,so 方法和 returns true 如果任何元素已被删除:

public void removeVehicle() {
    Scanner input = new Scanner(System.in);
    System.out.println("## Remove Vehicle from Inventory ##");
    System.out.print("Enter the Vehicle Index Number: ");
    int indexRemove = input.nextInt();

    if (vehicleList.removeIf(car -> indexRemove == car.getIndex())) {
        System.out.println("Vehicle Removed Successfully");
    } else {
        System.out.println("No Such Vehicle Exists");
    }
}

正如您请求的 updateVehicle 方法,您可以使用以下代码, 但是有了这个,我建议你覆盖 toString() 方法,如果你覆盖 hashcode 和 equals 方法更好

public static void updateVehicle() {
    Scanner input = new Scanner(System.in);
    System.out.println("## Upadate Vehicle by index number ##");
    System.out.print("Enter the Vehicle Index Number: ");        
    int indexRemove = input.nextInt();
    ListIterator<Automobile> listIterator = vehicleList.listIterator();
    boolean updated = false;
    while(listIterator.hasNext()) {
        Automobile mobile = listIterator.next(); 
        if(mobile.getIndex()==indexRemove) {
            
            System.out.println("Existing details : "+mobile.toString());
            
            System.out.print("Enter Vehicle make: ");
            String make = input.nextLine();
            System.out.print("Enter Vehicle model: ");
            String model = input.nextLine();
            System.out.print("Enter Vehicle color: ");
            String color = input.nextLine();
            System.out.print("Enter Vehicle year: ");
            int year = input.nextInt();
            System.out.print("Enter Vehicle mileage: ");
            int mileage = input.nextInt();
            
            mobile.setMake(make);
            mobile.setModel(model);
            mobile.setModel(model);
            mobile.setColor(color);
            mobile.setYear(year);
            mobile.setMileage(mileage);
            
            
            updated = true;
            break;
        }
    }
    if(updated) {
        System.out.println("Vehicle Updated Successfully");
    }
    else {
        System.out.println("No Such Vehicle Exists");
    }
}