此代码要求用户输入具有名称、型号年份、上市价格和折扣百分比的车辆对象。这里发生的问题是,当用户输入上述所有信息时,汽车对象被添加到数组列表的底部,而不是按字母顺序。请注意,该列表之前是按字母顺序排列的。
while (!valid) {
String str = scan.nextLine();
try {
boolean found = false;
System.out.println("Enter car name: ");
name = scan.nextLine();
System.out.println("Enter car model year: ");
modelYear = scan.nextLine();
System.out.println("Enter car list price: ");
listPrice = scan.nextDouble();
System.out.println("Enter car percent discount: ");
percentDiscount = scan.nextDouble();
int i = 0;
loc = 0;
while (!found && i < carList.size()) {
String nameRetrievedFromCarList = carList.get(i).getName();
String nameToAdd = "";
if (nameToAdd.compareToIgnoreCase(nameRetrievedFromCarList) < 0) {
loc++;
found = true;
}
i++;
}// end while
Proj1CarData newCar = new Proj1CarData(name, modelYear, listPrice, percentDiscount,
discountAmount, netPrice);
carList.add(loc, newCar);
valid = true;
}// end try
catch (NumberFormatException nfe) {
System.out.println("Wrong entry: Try again");
}// end catch
}