因此,我正在为汽车经销商编写程序,这是我班的最后一个项目。这时候我要说大约完成了75%,但是在弄清楚如何更新数组列表中的用户输入时遇到了麻烦。因此,每个阵列列表插槽均包含汽车的年份,品牌,型号,颜色和行驶里程。我可以添加新车,可以移除车,然后退出程序。我已经尝试了很多事情,读了许多论文,博客,论坛和我的课堂书籍,但是它总是随着程序员的输入而更新。
package carDealer;
import java.util.ArrayList;
import java.util.Scanner;
public class VehicleInformation {
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<VehicleInventory> car = new ArrayList<VehicleInventory>();
String userInput = "-";
while (!userInput.equals("q")) {
System.out.println("Commands: 'a' to add, 'd' to delete, 'e' to edit, 'q' to quit");
userInput = scnr.next();
if (userInput.equals("a")) {
System.out.println("Year: ");
int year = scnr.nextInt();
System.out.println("Make: ");
String make = scnr.next();
System.out.println("Model: ");
String model = scnr.next();
System.out.println("Color: ");
String color = scnr.next();
System.out.println("Mileage: ");
int mileage = scnr.nextInt();
VehicleInventory userCar = new VehicleInventory();
userCar.setMake(make);
userCar.setModel(model);
userCar.setYear(year);
userCar.setColor(color);
userCar.setMileage(mileage);
userCar.print();
addCar(car, userCar);
}
if (userInput.equals("d")) {
for (int i = 0; i < car.size(); ++i) {
System.out.print((i + 1) + " ");
car.get(i).print();
}
System.out.println("List number: ");
int userNum = scnr.nextInt();
car.remove(userNum - 1);
System.out.println("count: " + car.size());
}
if (userInput.equals("e")) {
for (int i = 0; i < car.size(); ++i) {
System.out.print((i + 1) + " ");
car.get(i).print();
}
System.out.println("List number: ");
int userNum = scnr.nextInt();
car.get(userNum - 1);
答案 0 :(得分:0)
您可以做一个循环来查找用户想要更新的汽车模型(可以是任何其他属性),一旦找到要更新的模型,其值即为所需值:
String vehicleToLookUp = "golf"; // This will be received by user input
String vehicleNewName = "golf gti"; // This will be received by user input
for( int i = 0; i < car.size(); i++){
if(vehicleToLookUp.getModel().equals(car.get(i)){
car.get(i).setSomeAttribute(...); // Set the desired attribute here
}
}
或者如果您想替换整个对象...
String vehicleToLookUp = "golf"; // This will be received by user input
VehicleInventory newVehicle = new VehicleInventory(); // You will set the attributes by user input
for( int i = 0; i < car.size(); i++){
if(vehicleToLookUp.getModel().equals(car.get(i)){
car.set(i, newVehicle ); // Create your object and pass it here
}
}
此外,您可以使用if
甚至使用if/else if
代替所有的switch/case
,以获得更好的性能/可读性(请考虑,即使您的逻辑对于第一个{{1 }},它将检查您创建的所有其他if
,浪费时间和处理能力。