如何通过匹配价格获取特定名称

发布于 2025-01-27 03:04:00 字数 443 浏览 3 评论 0原文

在此如何通过从用户输入价格来获取汽车名称。

public static void main(String[] args) {
    Car toyota = new Car("Toyota", "$10000", "300" + "2003");
    Car nissan = new Car("Nissan", "$22000", "300" + "2011");
    Car ford = new Car("Ford", "$15000", "350" + "2010");

    ArrayList<Car> cars = new ArrayList<Car> ();
    cars.add(toyota);
    cars.add(nissan);
    cars.add(ford);
}

In this how to get car name by entering price from user.

public static void main(String[] args) {
    Car toyota = new Car("Toyota", "$10000", "300" + "2003");
    Car nissan = new Car("Nissan", "$22000", "300" + "2011");
    Car ford = new Car("Ford", "$15000", "350" + "2010");

    ArrayList<Car> cars = new ArrayList<Car> ();
    cars.add(toyota);
    cars.add(nissan);
    cars.add(ford);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半岛未凉 2025-02-03 03:04:01

关于价格搜索的事情是,除非您可以使用价格范围搜索,否则搜索某些东西确实不好恰好是您正在搜索的项目。此外,价格并不总是四舍五入到最接近的一千,因此,如果您想根据价格为10000(无论是面额)的物品搜索物品,那么您会错过那些10324、10156.99等的物品但是。当然,您可以通过代码将其源为自动应用范围,从而为所提供的价格提供上限值。如果需要,下面可运行的方法实际上可以做到这一点。

在代码中阅读评论:

public class CarMakesFromCarValueDemo {

    public final String LS = System.lineSeparator();
    public final static java.util.Scanner userInput = new java.util.Scanner(System.in);
    public static java.util.List<Car> cars = new java.util.ArrayList<>();

    public CarMakesFromCarValueDemo() {
        //                Make      Model        Serial Number      Odometer  Price    Year  
        cars.add(new Car("Toyota", "Corolla",   "G783372453H499215", 232532, "$10000", 2003));
        cars.add(new Car("Nissan", "Sentra",    "KS994788291983GF6", 113661, "$22000", 2017));
        cars.add(new Car("Ford",   "F-150 4DR", "822F5543654G53334", 164191, "$15000", 2010));
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // App Started this way to avoid the need for statics.
        new CarMakesFromCarValueDemo().startApp(args);
    }

    private void startApp(String[] args) {
        // For lack of a better name at the moment...
        System.out.println("Used Cars Data Center" + LS  
                         + "=====================");
        while (true) {
        // Demo method...
            String result = getVehiclesOnPriceRange();
            if (result.equalsIgnoreCase("c")) {
                break;
            }
        }
        
        /* Things To Do....
           1) Create a method to handle Command -Line arguments.
        
           2) Create a Maain Menu system so as to initiate the following:
                - Add Cars to the Collection. Serial Number can be no more than the 
                  legal 17 characters. Vehicle prices can be in Whole or Floating
                  Point numbering system however, although not mandatory, the entire 
                  Base should be in one or the other format. Because prices can be 
                  in either numerical format, they should be stored as String. See 
                  the getVehiclesOnPriceRange() method for how to handle `either or`.
                - Edit a Car's instance data.
                - Delete Cars from the Collection with an "Are You Sure?" feature. 
                - List all available Cars (utilizing the Car.toStringTable() method).
                - Search for all Cars by Make, Model, Serial Number or part thereof, 
                  Odometer Reading Range, Price [method already created as Demo], 
                  or by Year or Year Range. The type of search must be selectable 
                  via a Sub-Menu.
                - Quit the application with an "Are You Sure?" feature.
              Main Menu should continuously loop until 'q' for quit is selected.
        
           3) Auto-Load the Cars Collection from a Text file (if it exists) when 
              the application starts.
        
           4) Auto-Save the Cars Collection to a Text file when changes to the Cars
              Collection via additions, edits, or deletions.
        
           5) The ability to Print (to local Printer) any Listings or Searches.
        
           Make necessary modifications to existing code where you see fit.
           Have fun!
        */
    }

    /**
     * Retrieves and displays a List of available Cars contained within the List 
     * collection based on a supplied price or price range. When prompted, a valid 
     * price can be supplied in several different ways. The price value provided 
     * can be either whole numbers, floating point numbers, or both. Here are 
     * examples of valid price entries:<pre>
     * 
     *     5000   or  5434.99      nnn[.nn] exact price.
     *     5000-  or  5003.54-     nnn[.nn] to Highest Priced Car in Collection.     
     *     -25000 or  -36452.88    0 to nnn[.nn] Price Range.
     *     5000-25312.98           nnn[.nn] to nnn[.nn] Price Range.
     * </pre>
     * All other entry types will be considered invalid. If a price range is 
     * supplied then the lower price value should always preceed the higher 
     * price value otherwise vehicles will likely NOT be found.<br><br>
     * 
     * The letter 'c' (in any letter case) can be supplied to cancel the search 
     * process.<br><br>
     * 
     * To understand the Regular Expression (regex) use for entry validation just 
     * go to <a href="https://regex101.com/r/xxrCjs/1">regex101.com</a> and read 
     * the explanation within the far right pane displayed.<br><br>
     * 
     * @param autoApplyUpperRange (Optional - double varArgs) Only one value is 
     * permitted. By default the autoApplyUpperRange value is 0.0 which basically 
     * means it does nothing. If however, you supply a whole or floating point 
     * value to this method's optional parameter then when a single value is supplied 
     * into the prompt, that supplied optional value creates a range of the supplied 
     * prompt value to the supplied prompt value plus the auto-apply value. In other 
     * words, if this method was supplied an optional value of 500 (or 500.00) and 
     * at the prompt generated by the method, the User enters 10000 then the actual
     * price range will be: 10000-10500. If nothing was supplied to this optional 
     * parameter then there would be no range, the search would require an exact 
     * match of 10000 for a price.<br><br>
     * 
     * The argument supplied to this parameter will only apply to non-ranged price 
     * values supplied within the method's prompt. It will never apply to ranged 
     * entries.<br>
     * 
     * @return (String) The price or Price Range provided within the method's prompt.
     */
    public String getVehiclesOnPriceRange(double... autoApplyUpperRange) {
        // Are there cars available?
        if (cars.isEmpty()) {
            System.out.println("----------------------------" + LS
                             + "There are no Cars available!" + LS
                             + "----------------------------" + LS);
            return "";
        }
        
        //Auto Range
        double autoUpperRange = 0.0d;
        if (autoApplyUpperRange.length > 0) {
            if (String.valueOf(autoApplyUpperRange[0]).matches("\\d+(\\.\\d+)?")) {
                autoUpperRange = autoApplyUpperRange[0];
            }
        }
        
        //Prompt...
        System.out.println();
        System.out.println("Vehicle Price Search:" + LS + "---------------------");
        String desiredPrice = "";
        while (desiredPrice.isEmpty()) {
            System.out.println("Please enter the desired vehicle price or price range.");
            System.out.println("(valid entries: 10000 or 6000-12000 or 6000- or -12000)");
            System.out.print("Enter 'c' to cancel: --> ");
            desiredPrice = userInput.nextLine().trim();
            if (desiredPrice.equalsIgnoreCase("c")) {
                System.out.println("----------------------");
                System.out.println("Price Search Canceled!");
                System.out.println("----------------------" + LS);
                return "c";
            }
            
            // Entry Validation...
            if (!desiredPrice.matches("(\\d+(\\.\\d+)?)|(\\d+(\\.\\d+)?)?(\\s*-\\s*)(\\d+(\\.\\d+)?)?")
                    || desiredPrice.replace("-", "").isEmpty()) {
                System.out.println("Invalid Price or Price Range Entry (" + desiredPrice + ")! Try again..." + LS);
                desiredPrice = "";
            }
        }
        if (autoUpperRange != 0.0d && !desiredPrice.contains("-")) {
                desiredPrice += "-" + String.valueOf(Double.parseDouble(desiredPrice) + autoUpperRange);
        }
        
        System.out.println();
        System.out.println("Cars Available Based On Price Range: " + desiredPrice);

        // Get the highest priced vehicle in cars collection (used for nnnn- range entry).
        double highestValuedCarDbl = 0.0d;
        for (Car c : cars) {
            String mPrice = c.getPrice();
            double p = Double.parseDouble(mPrice);
            if (p > highestValuedCarDbl) {
                highestValuedCarDbl = p;
            }
        }
        
        int foundCounter = 0;
        
        // Price Range...
        double lowerValueDbl = 0.0d, upperValueDbl = 0.0d;
        if (desiredPrice.contains("-")) {
            String[] priceParts = desiredPrice.split("\\s*\\-\\s*");
            // Price range entry of nnnn-
            if (priceParts.length == 1) {
                lowerValueDbl = priceParts[0].isEmpty() ? 0.0d : Double.parseDouble(priceParts[0]);
                upperValueDbl = highestValuedCarDbl;
            }
            // Price range entry of -nnnn OR nnnn-nnnn
            else if (priceParts.length >= 1) {
                /* If the entry is -nnnn then 0 is used for the low value
                   otherwise the entry supplied must be nnnn-nnnn therefore
                   the value itself is used. `Ternary Operator` is used here
                   to determine this.*/
                lowerValueDbl = priceParts[0].isEmpty() ? 0.0d : Double.parseDouble(priceParts[0]);
            }
            // The high value of the nnnn-nnnn range entry.
            if (priceParts.length >= 2) {
                upperValueDbl = priceParts[1].isEmpty() ? 0.0d : Double.parseDouble(priceParts[1]);
            }

            for (Car car : cars) {
                String price = car.getPrice();
                    double carPrice = Double.parseDouble(price);
                if (carPrice >= lowerValueDbl && carPrice <= upperValueDbl) {
                    if (foundCounter == 0) {
                        System.out.println(car.toStringTable(true));
                    }
                    else {
                        System.out.println(car.toStringTable());
                    }
                    foundCounter++;
                }
            }
        }
        // Specific Price...
        else {
            double desPrice = Double.parseDouble(desiredPrice);
            for (Car car : cars) {
                String price = car.getPrice();
                double carPrice = Double.parseDouble(price);
                if (carPrice == desPrice) {
                    if (foundCounter == 0) {
                        System.out.println(car.toStringTable(true));
                    }
                    else {
                        System.out.println(car.toStringTable());
                    }
                    foundCounter++;
                }
            }
        }
        
        if (foundCounter == 0) {
            System.out.println("--------------" + LS 
                             + "No Cars Found!" + LS 
                             + "--------------" + LS); 
            return desiredPrice;
        }
        
        // Final table underline.
        if (!cars.isEmpty()) {
            System.out.println(cars.get(0).tableUnderline); //.replace("=", "-"));
        }
        return desiredPrice;
    }
}

汽车类:

public class Car {
    
    private String make;
    private String model;
    private String serialNumber;
    private int odometerReading;
    private String price;
    private int vehicleYear;
    public String tableUnderline = "";

    public Car(String make, String model, String serialNumber, 
               int odometerReadeing, String price, int vehicleYear) {
        this.make = make;
        this.model = model;
        this.serialNumber = serialNumber;
        this.odometerReading = odometerReadeing;
        this.price = price.replaceAll("[^0-9.]", "");
        this.vehicleYear = vehicleYear;
    }

    public String getMake() {
        return make;
    }

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

    public String getPrice() {
        return price;
    }
    
    public double getPriceAsDouble() {
        return Double.parseDouble(price);
    }

    public void setPrice(String price) {
        this.price = price.replaceAll("[^0-9.]", "");
    }

    public String getModel() {
        return model;
    }

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

    public String getSerialNumber() {
        return serialNumber;
    }

    public void setSerialNumber(String serialNumber) {
        this.serialNumber = serialNumber;
    }

    public int getOdometerReading() {
        return odometerReading;
    }

    public void setOdometerReading(int odometerReading) {
        this.odometerReading = odometerReading;
    }

    public int getVehicleYear() {
        return vehicleYear;
    }

    public void setVehicleYear(int vehicleYear) {
        this.vehicleYear = vehicleYear;
    }
    
    @Override
    public String toString() {
        final String cs = java.util.Currency.getInstance(java.util.Locale.getDefault()).getSymbol();
        return make + ", " + model + ", " + serialNumber + ", " + odometerReading 
                    + ", " + cs + price + ", " + vehicleYear;
    }
    
    public String toStringTable(Boolean... addHeader) {
        final String LS = System.lineSeparator();
        String cs = java.util.Currency.getInstance(java.util.Locale.getDefault()).getSymbol();
        boolean applyHeader = false;
        
        if (addHeader != null && addHeader.length > 0) {
            applyHeader = addHeader[0];
        }
        String header = String.format("%-10s %-12s %-19s %-10s %-10s %-4s", "Make", 
                                      "Model", "Serial Number", "Odometer", "Price", 
                                      "Year");
        this.tableUnderline = String.join("", java.util.Collections.nCopies(header.length(), "="));
        StringBuilder sb = new StringBuilder("");
        if (applyHeader) {
            sb.append(this.tableUnderline.replace("=", "-")).append(LS).append(header)
                      .append(LS).append(this.tableUnderline).append(LS);
        }
        sb.append(String.format("%-10s %-12s %-19s %-10s " + cs + "%-9s %-4s", 
                                this.make, this.model, this.serialNumber, 
                                this.odometerReading, this.price, this.vehicleYear));
        return sb.toString();
    }
}

The thing about price searching is that it really is no good to search for something unless you can search with a price range, unless of course you happen to know exactly what the price happens to be for the item(s) you're searching. Also, prices are not always rounded to the nearest thousand, so if you want to carry out a search for an item based on say a price of 10000 (whatever denomination) then you will miss those items that are 10324, 10156.99, etc, etc. A range however of: 10000-10999 would most likely be a more viable option. Of course you can source this in code to automatically apply a range by providing an upper range value to the price supplied. The method provided in the runnable below can actually do this if so desired.

Read the comments in code:

public class CarMakesFromCarValueDemo {

    public final String LS = System.lineSeparator();
    public final static java.util.Scanner userInput = new java.util.Scanner(System.in);
    public static java.util.List<Car> cars = new java.util.ArrayList<>();

    public CarMakesFromCarValueDemo() {
        //                Make      Model        Serial Number      Odometer  Price    Year  
        cars.add(new Car("Toyota", "Corolla",   "G783372453H499215", 232532, "$10000", 2003));
        cars.add(new Car("Nissan", "Sentra",    "KS994788291983GF6", 113661, "$22000", 2017));
        cars.add(new Car("Ford",   "F-150 4DR", "822F5543654G53334", 164191, "$15000", 2010));
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // App Started this way to avoid the need for statics.
        new CarMakesFromCarValueDemo().startApp(args);
    }

    private void startApp(String[] args) {
        // For lack of a better name at the moment...
        System.out.println("Used Cars Data Center" + LS  
                         + "=====================");
        while (true) {
        // Demo method...
            String result = getVehiclesOnPriceRange();
            if (result.equalsIgnoreCase("c")) {
                break;
            }
        }
        
        /* Things To Do....
           1) Create a method to handle Command -Line arguments.
        
           2) Create a Maain Menu system so as to initiate the following:
                - Add Cars to the Collection. Serial Number can be no more than the 
                  legal 17 characters. Vehicle prices can be in Whole or Floating
                  Point numbering system however, although not mandatory, the entire 
                  Base should be in one or the other format. Because prices can be 
                  in either numerical format, they should be stored as String. See 
                  the getVehiclesOnPriceRange() method for how to handle `either or`.
                - Edit a Car's instance data.
                - Delete Cars from the Collection with an "Are You Sure?" feature. 
                - List all available Cars (utilizing the Car.toStringTable() method).
                - Search for all Cars by Make, Model, Serial Number or part thereof, 
                  Odometer Reading Range, Price [method already created as Demo], 
                  or by Year or Year Range. The type of search must be selectable 
                  via a Sub-Menu.
                - Quit the application with an "Are You Sure?" feature.
              Main Menu should continuously loop until 'q' for quit is selected.
        
           3) Auto-Load the Cars Collection from a Text file (if it exists) when 
              the application starts.
        
           4) Auto-Save the Cars Collection to a Text file when changes to the Cars
              Collection via additions, edits, or deletions.
        
           5) The ability to Print (to local Printer) any Listings or Searches.
        
           Make necessary modifications to existing code where you see fit.
           Have fun!
        */
    }

    /**
     * Retrieves and displays a List of available Cars contained within the List 
     * collection based on a supplied price or price range. When prompted, a valid 
     * price can be supplied in several different ways. The price value provided 
     * can be either whole numbers, floating point numbers, or both. Here are 
     * examples of valid price entries:<pre>
     * 
     *     5000   or  5434.99      nnn[.nn] exact price.
     *     5000-  or  5003.54-     nnn[.nn] to Highest Priced Car in Collection.     
     *     -25000 or  -36452.88    0 to nnn[.nn] Price Range.
     *     5000-25312.98           nnn[.nn] to nnn[.nn] Price Range.
     * </pre>
     * All other entry types will be considered invalid. If a price range is 
     * supplied then the lower price value should always preceed the higher 
     * price value otherwise vehicles will likely NOT be found.<br><br>
     * 
     * The letter 'c' (in any letter case) can be supplied to cancel the search 
     * process.<br><br>
     * 
     * To understand the Regular Expression (regex) use for entry validation just 
     * go to <a href="https://regex101.com/r/xxrCjs/1">regex101.com</a> and read 
     * the explanation within the far right pane displayed.<br><br>
     * 
     * @param autoApplyUpperRange (Optional - double varArgs) Only one value is 
     * permitted. By default the autoApplyUpperRange value is 0.0 which basically 
     * means it does nothing. If however, you supply a whole or floating point 
     * value to this method's optional parameter then when a single value is supplied 
     * into the prompt, that supplied optional value creates a range of the supplied 
     * prompt value to the supplied prompt value plus the auto-apply value. In other 
     * words, if this method was supplied an optional value of 500 (or 500.00) and 
     * at the prompt generated by the method, the User enters 10000 then the actual
     * price range will be: 10000-10500. If nothing was supplied to this optional 
     * parameter then there would be no range, the search would require an exact 
     * match of 10000 for a price.<br><br>
     * 
     * The argument supplied to this parameter will only apply to non-ranged price 
     * values supplied within the method's prompt. It will never apply to ranged 
     * entries.<br>
     * 
     * @return (String) The price or Price Range provided within the method's prompt.
     */
    public String getVehiclesOnPriceRange(double... autoApplyUpperRange) {
        // Are there cars available?
        if (cars.isEmpty()) {
            System.out.println("----------------------------" + LS
                             + "There are no Cars available!" + LS
                             + "----------------------------" + LS);
            return "";
        }
        
        //Auto Range
        double autoUpperRange = 0.0d;
        if (autoApplyUpperRange.length > 0) {
            if (String.valueOf(autoApplyUpperRange[0]).matches("\\d+(\\.\\d+)?")) {
                autoUpperRange = autoApplyUpperRange[0];
            }
        }
        
        //Prompt...
        System.out.println();
        System.out.println("Vehicle Price Search:" + LS + "---------------------");
        String desiredPrice = "";
        while (desiredPrice.isEmpty()) {
            System.out.println("Please enter the desired vehicle price or price range.");
            System.out.println("(valid entries: 10000 or 6000-12000 or 6000- or -12000)");
            System.out.print("Enter 'c' to cancel: --> ");
            desiredPrice = userInput.nextLine().trim();
            if (desiredPrice.equalsIgnoreCase("c")) {
                System.out.println("----------------------");
                System.out.println("Price Search Canceled!");
                System.out.println("----------------------" + LS);
                return "c";
            }
            
            // Entry Validation...
            if (!desiredPrice.matches("(\\d+(\\.\\d+)?)|(\\d+(\\.\\d+)?)?(\\s*-\\s*)(\\d+(\\.\\d+)?)?")
                    || desiredPrice.replace("-", "").isEmpty()) {
                System.out.println("Invalid Price or Price Range Entry (" + desiredPrice + ")! Try again..." + LS);
                desiredPrice = "";
            }
        }
        if (autoUpperRange != 0.0d && !desiredPrice.contains("-")) {
                desiredPrice += "-" + String.valueOf(Double.parseDouble(desiredPrice) + autoUpperRange);
        }
        
        System.out.println();
        System.out.println("Cars Available Based On Price Range: " + desiredPrice);

        // Get the highest priced vehicle in cars collection (used for nnnn- range entry).
        double highestValuedCarDbl = 0.0d;
        for (Car c : cars) {
            String mPrice = c.getPrice();
            double p = Double.parseDouble(mPrice);
            if (p > highestValuedCarDbl) {
                highestValuedCarDbl = p;
            }
        }
        
        int foundCounter = 0;
        
        // Price Range...
        double lowerValueDbl = 0.0d, upperValueDbl = 0.0d;
        if (desiredPrice.contains("-")) {
            String[] priceParts = desiredPrice.split("\\s*\\-\\s*");
            // Price range entry of nnnn-
            if (priceParts.length == 1) {
                lowerValueDbl = priceParts[0].isEmpty() ? 0.0d : Double.parseDouble(priceParts[0]);
                upperValueDbl = highestValuedCarDbl;
            }
            // Price range entry of -nnnn OR nnnn-nnnn
            else if (priceParts.length >= 1) {
                /* If the entry is -nnnn then 0 is used for the low value
                   otherwise the entry supplied must be nnnn-nnnn therefore
                   the value itself is used. `Ternary Operator` is used here
                   to determine this.*/
                lowerValueDbl = priceParts[0].isEmpty() ? 0.0d : Double.parseDouble(priceParts[0]);
            }
            // The high value of the nnnn-nnnn range entry.
            if (priceParts.length >= 2) {
                upperValueDbl = priceParts[1].isEmpty() ? 0.0d : Double.parseDouble(priceParts[1]);
            }

            for (Car car : cars) {
                String price = car.getPrice();
                    double carPrice = Double.parseDouble(price);
                if (carPrice >= lowerValueDbl && carPrice <= upperValueDbl) {
                    if (foundCounter == 0) {
                        System.out.println(car.toStringTable(true));
                    }
                    else {
                        System.out.println(car.toStringTable());
                    }
                    foundCounter++;
                }
            }
        }
        // Specific Price...
        else {
            double desPrice = Double.parseDouble(desiredPrice);
            for (Car car : cars) {
                String price = car.getPrice();
                double carPrice = Double.parseDouble(price);
                if (carPrice == desPrice) {
                    if (foundCounter == 0) {
                        System.out.println(car.toStringTable(true));
                    }
                    else {
                        System.out.println(car.toStringTable());
                    }
                    foundCounter++;
                }
            }
        }
        
        if (foundCounter == 0) {
            System.out.println("--------------" + LS 
                             + "No Cars Found!" + LS 
                             + "--------------" + LS); 
            return desiredPrice;
        }
        
        // Final table underline.
        if (!cars.isEmpty()) {
            System.out.println(cars.get(0).tableUnderline); //.replace("=", "-"));
        }
        return desiredPrice;
    }
}

The Car Class:

public class Car {
    
    private String make;
    private String model;
    private String serialNumber;
    private int odometerReading;
    private String price;
    private int vehicleYear;
    public String tableUnderline = "";

    public Car(String make, String model, String serialNumber, 
               int odometerReadeing, String price, int vehicleYear) {
        this.make = make;
        this.model = model;
        this.serialNumber = serialNumber;
        this.odometerReading = odometerReadeing;
        this.price = price.replaceAll("[^0-9.]", "");
        this.vehicleYear = vehicleYear;
    }

    public String getMake() {
        return make;
    }

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

    public String getPrice() {
        return price;
    }
    
    public double getPriceAsDouble() {
        return Double.parseDouble(price);
    }

    public void setPrice(String price) {
        this.price = price.replaceAll("[^0-9.]", "");
    }

    public String getModel() {
        return model;
    }

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

    public String getSerialNumber() {
        return serialNumber;
    }

    public void setSerialNumber(String serialNumber) {
        this.serialNumber = serialNumber;
    }

    public int getOdometerReading() {
        return odometerReading;
    }

    public void setOdometerReading(int odometerReading) {
        this.odometerReading = odometerReading;
    }

    public int getVehicleYear() {
        return vehicleYear;
    }

    public void setVehicleYear(int vehicleYear) {
        this.vehicleYear = vehicleYear;
    }
    
    @Override
    public String toString() {
        final String cs = java.util.Currency.getInstance(java.util.Locale.getDefault()).getSymbol();
        return make + ", " + model + ", " + serialNumber + ", " + odometerReading 
                    + ", " + cs + price + ", " + vehicleYear;
    }
    
    public String toStringTable(Boolean... addHeader) {
        final String LS = System.lineSeparator();
        String cs = java.util.Currency.getInstance(java.util.Locale.getDefault()).getSymbol();
        boolean applyHeader = false;
        
        if (addHeader != null && addHeader.length > 0) {
            applyHeader = addHeader[0];
        }
        String header = String.format("%-10s %-12s %-19s %-10s %-10s %-4s", "Make", 
                                      "Model", "Serial Number", "Odometer", "Price", 
                                      "Year");
        this.tableUnderline = String.join("", java.util.Collections.nCopies(header.length(), "="));
        StringBuilder sb = new StringBuilder("");
        if (applyHeader) {
            sb.append(this.tableUnderline.replace("=", "-")).append(LS).append(header)
                      .append(LS).append(this.tableUnderline).append(LS);
        }
        sb.append(String.format("%-10s %-12s %-19s %-10s " + cs + "%-9s %-4s", 
                                this.make, this.model, this.serialNumber, 
                                this.odometerReading, this.price, this.vehicleYear));
        return sb.toString();
    }
}
弱骨蛰伏 2025-02-03 03:04:00

如果使用Java版本&gt; = 8,则可以使用流。

private List<String> getCarNamesByPrice(ArrayList<Car> cars, String price) {
    return cars.stream()
               .map(Car::Price)
               .filter(p -> p == price)
               .collect(Collectors.toList());
}

If you are using java version >= 8, you can use streams.

private List<String> getCarNamesByPrice(ArrayList<Car> cars, String price) {
    return cars.stream()
               .map(Car::Price)
               .filter(p -> p == price)
               .collect(Collectors.toList());
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文