首页 > 解决方案 > 如何获得正确的输入来获取我的 ArrayList 的索引?

问题描述

我正在尝试通过 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);

}    

我已经复制了调试器显示给我的值并用它替换了它们,但它似乎仍然不起作用。我是否接受了错误类型的数据?我可以尝试什么?

如果我的代码看起来有问题,我总是会努力让它变得更好。

标签: javaooparraylist

解决方案


你不能用 a 来做Map<String, Shop>吗?这样你就可以使用shopName作为键。

顺便说一句,当我看到您使用 java 和 OOP 的新知识时,我强烈建议您阅读 Robert C. Martin 的 Clean Code,这是一本改变游戏规则的书。


推荐阅读