从输入

时间:2016-06-01 13:12:50

标签: java arrays arraylist

我有一个这样的数组:

1101 "TV"
5531 "Baju Baru"
1425 "Mesin Cuci"

然后我想删除" TV"来自我的Arraylist。所以我必须键入" 1101"然后删除该值。但是,如果我错了,它会显示"代码无效"。

这是我的代码:

for (int i = 0; i < listBarang.size(); i++) {
    System.out.println(listBarang.get(i));
}
System.out.println("Your code stuff: ");
int code = Integer.parseInt(input.next());
listBarang.remove(i);

任何答案?

2 个答案:

答案 0 :(得分:1)

考虑使用Map存储阵列,您可以从中删除TV元素。试试这个。

Map<Integer,String> map = new HashMap<>();
    map.put(1101,"TV");
    map.put(5531 ,"Baju Baru");
    map.put(1425 ,"Mesin Cuci");

    for (Map.Entry<Integer,String> hh : map.entrySet()) {
        if (hh.getKey() == 1101){
            map.remove(hh.getKey());
        }
    }

    System.out.println(map);

没有“电视”的输出

{1425=Mesin Cuci, 5531=Baju Baru}

答案 1 :(得分:0)

删除(i)在循环之外没有任何意义。将其移入内部,如果代码等于输入remove(i)。