【问题标题】:Remove from ArrayList based on user input根据用户输入从 ArrayList 中删除
【发布时间】:2021-07-27 17:46:55
【问题描述】:

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

我用 set 和 get 方法构建了一个汽车类:

    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 类中,我现在有一个看起来可以工作的 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");
        }

    }

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

【问题讨论】:

    标签: java arraylist


    【解决方案1】:

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

    解决方案 1

    我几乎创建了一个 foreach 循环,它遍历您现有的列表并通过提供的索引检查是否存在。然后它在 if 语句中将其删除。如果成功删除,则为真,否则为假。

       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");
            }
        }
    

    MISC 导出:

            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.");
            }
        }
    

    【讨论】:

    • 非常感谢。感谢您花时间提供多种解决方案。我可以在解决方案 2 的 if/else 语句中轻松实现 try/catch 吗?
    • 我能看到你实现 try/catch 的唯一地方是“int indexRemove = input.nextInt();”如果有人给你一个字符串而不是一个数字。我将其添加为解决方案 4。
    • 有趣。但实际上,使用我的 removeVehicle 方法,如果输入的不是适用的索引号,那么它会给出“不存在这样的车辆”,对吗?我需要在某个地方尝试/捕获,所以我正在考虑将它包含在我必须构建的 printFile() 方法中。它需要显示一条消息,询问用户是否要将信息打印到文件(是或否),然后将文件打印到预定义的位置(例如,C:\Temp\Autos.txt)。我还不是 100% 确定那会是什么样子,但感觉就像是正确的道路。想法?
    • 如果需要,您可以在打印文件上执行此操作,但我刚刚更新了解决方案 4,如果他们在 int 之外输入任何内容,则显示“不存在此类车辆”。
    • 我可以完全理解解决方案 2,它是目前对我来说最有意义的一个。从知识的角度来看,增强 for 循环的简单性与我所处的位置有关。您建议从哪里开始打印文件?您的解决方案 3 会打印整个库存,但将其写入文件则是另一回事。
    【解决方案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();
    
        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");
        }
    }
    

    【讨论】:

      【解决方案3】:

      尝试使用 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");
          }
      }
      

      【讨论】:

      • 我一直在尝试将 ListIterator 用于库存的“更新车辆”部分。我需要它来更新车辆,打印返回值,然后调用列表方法并将信息打印到屏幕上。我想我很接近,但对这个功能很不熟悉。
      • public static &lt;AutoMobile&gt; void updateVehicle() { Scanner input = new Scanner(System.in); System.out.println("## Remove Vehicle from Inventory ##"); System.out.print("Enter the make of Automobile: "); String make = input.nextLine(); System.out.print("Enter the model of Automobile: "); String model = input.nextLine(); System.out.print("Enter the Vehicle Index Number: "); ListIterator&lt;AutoMobile&gt; iterator =(ListIterator&lt;AutoMobile&gt;) vehicleList.listIterator(); while(iterator.hasNext()){
      【解决方案4】:

      从 Java 8 开始,Collection(因此是List)具有方法removeIf (Predicate p),它允许删除满足应用于集合的每个元素的给定谓词的所有元素,因此方法并返回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");
          }
      }
      

      【讨论】:

        【解决方案5】:

        根据您对 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");
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2014-02-06
          • 2017-02-28
          • 2017-01-11
          • 2017-02-10
          • 1970-01-01
          • 1970-01-01
          • 2022-11-14
          • 2023-04-10
          • 1970-01-01
          相关资源
          最近更新 更多