我正在尝试通过indexOf获取ArrayList的索引。到目前为止,我有
我的阵列列表:public static ArrayList<Shop> allShops = new ArrayList();
应该得到索引的东西
Scanner editShop = new Scanner(System.in);
String shopToEdit = editShop.nextLine();
int i = allShops.indexOf(shopToEdit);
System.out.println(i); //see what our index is (returns -1 because the var doesn't seem to get the right input)
EditFunc.edit(i);
而这个,这应该改变我的数组列表
public static void edit(int index){
//change array with given input in edit
//TODO: Make it so they can choose what to edit
//with booleans if editTrueName = false and then later on make it true again
System.out.println("Enter the new shop name:");
Scanner editedShopAttribute = new Scanner(System.in);
String editedShopName = editedShopAttribute.nextLine();
System.out.println("Enter the new shop location:");
String editedShopLocation = editedShopAttribute.nextLine();
Shop EditedVar = new Shop();
EditedVar.createShop(editedShopName,editedShopLocation);
allShops.set(index, EditedVar);
}
我已经复制了调试器向我显示的值并用它替换了它们,但它似乎仍然不起作用。我是否接收了错误类型的数据?我可以尝试什么?
如果我的代码看起来有问题,我总是会尝试让它变得更好。
你不能用Map<String, Shop>
来做吗?这样,您就可以将shopName
用作密钥。
顺便说一下,当我看到你对java和OOP的新东西时,我强烈建议你阅读Robert C. Martin的Clean Code,这是一本改变游戏规则的书。
我不相信你可以用数组来制作你想要的东西。 其中一条评论中指出的原因是您正在寻找一个字符串,但数组包含商店。 由于商店包含的不仅仅是商店名称,因此您将永远无法以这种方式找到它。 您应该将"地图"用于以下目的:
public static Map<String, Shop> allShopsMap = new HashMap<>();
如果您将所有商店添加到此地图中,那么当您获得 ShopName 作为输入时,您只需要执行以下操作:
Shop shopToEdit = allShopsMap.get(inputShopName);
然后调用此对象上的 SET 方法以更改名称和位置。