在数组中搜索元素并返回它

时间:2013-05-16 01:47:16

标签: java arrays methods return

以下方法始终返回NULL:

public SalesItem findItem(String itemCode){

        // to be implemented
        Cart cart = new Cart();
        SalesItem[] item;
        item = new SalesItem[1];
        item[0] = null;

        for (int i = 0; i < size -1; i++) {
          if (itemCode.equals(items[i].getItemCode())) {
            item[0] = items[i];
            System.out.println("Item - " + item +" is added to the shopping cart.");
            cart.addItem(items[i]);
          }

          else {
            item[0] = null;
          }
        }
        return item[0];

有人知道我的代码有什么问题吗?

2 个答案:

答案 0 :(得分:2)

如果for循环检查的最后一项与该项不匹配,则将item[0]设置为null。

然后您返回item[0]

因此for循环毫无意义。您可能应该找到找到的项目。

答案 1 :(得分:1)

你做到了 项[0] = NULL 并且你正在将itemCode与item [0]进行比较,它是equla为null,这就是为什么它总是返回null。

相关问题