【发布时间】:2020-10-03 18:23:31
【问题描述】:
我正在为汽车经销商开发一个 Java 程序。我正在使用增强的 for 循环遍历一组车辆,如果我输入匹配它的品牌和型号,我想返回一个匹配项。如果不匹配,我想返回“没有找到这样的车辆”,但只返回一次。现在,它返回 9 个“未找到”和 1 个匹配结果。我只想返回匹配的结果,如果没有,只有1个没有找到。
我有两个函数searchMakeModel() 和searchPriceRange()。我的searchMakeModel() 应该返回匹配的汽车,但由于某种原因它只是返回未找到。我的searchPriceRange() 工作,但我希望它只返回汽车。现在,如果汽车与价格范围不匹配,则返回 not found ;如果汽车与价格范围匹配,则返回汽车。
class CarDealer {
private Vehicle[] vehicleList;
private void searchMakeModel() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter vehicle make");
String make = scanner.nextLine();
System.out.println("Enter vehicle model");
String model = scanner.nextLine();
for(Vehicle vehicle: vehicleList) {
if(make == vehicle.getMake() && model == vehicle.getModel()) {
System.out.println(vehicle.getMake() + ";" + vehicle.getModel() + ";" + vehicle.getYear() + ";" + vehicle.getPrice());
} else {
System.out.println("No such vehicle is found");
}
}
}
private void searchPriceRange(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter min price: $");
double minPrice = scanner.nextDouble();
System.out.println("Enter max price: $");
double maxPrice = scanner.nextDouble();
for(Vehicle vehicle: vehicleList) {
if(minPrice <= vehicle.getPrice() && maxPrice >= vehicle.getPrice()) {
System.out.println(vehicle.getMake() + ";" + vehicle.getModel() + ";" + vehicle.getYear() + ";" + vehicle.getPrice());
break;
}
System.out.println("No vehicles in price range found");
}
}
}
【问题讨论】:
-
提示:在查看整个列表之前,不能说没有找到车辆。另外,您应该使用
equals来比较字符串... -
这两种方法都不返回任何内容。这就是“空”描述符的含义。