[英]How do I update a users input in an arraylist?
因此,我正在為汽車經銷商制定程序,這是我班的最后一個項目。 這時候我要說大約完成了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);
您可以做一個循環來查找用戶想要更新的汽車模型(它可以是任何其他屬性),一旦找到更新,它的值便與所需的模型相同:
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
以獲得更好的性能/可讀性(請考慮,即使您的邏輯首先是if
, if
創建,它將檢查所有其他內容,浪費時間和處理能力。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.