首页 > 解决方案 > 布尔值无法返回正确值

问题描述

我有四个班级客户,商店和物品以及在线。

我正在使用“LinkedList”来移动班级。

我在 Customer 类中添加了项目。

当我想检查在线课程下的项目是否存在时。

因为您无法在客户处查看。

我使用 hasItem()。它不断失败。

当我这么说时,我的意思是即使我输入了“001A:GTA”,该项目也存储在数据中并且它不起作用。它一直返回null。

有人可以向我解释吗?对此,我真的非常感激。我是一个完整的初学者。

物品等级

public class Item {
    private String code;
    private String name;
    public Item(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public boolean hasItem(String code, String name){
      return code.equals(this.code) && name.equals(this.name);
    }

    @Override
    public String toString() {
        return name + " : " + code;
    }

}

店铺类

    public class Store {
    private LinkedList<Item> items = new LinkedList<Item>();

    public Store(String name, String number) {
        this.name = name;
        this.number = number;
    }

    public void addItem(String code, String name){
          items.add(new Item(this, code, name);
       }

    public LinkedList<Item> viewItem(){
           for(int j = 0 ; j < items.size(); j++)
               System.out.println(items.get(j))
           return null; 
    }
}

顾客

   public class Customer {
    private LinkedList<Store> stores = new LinkedList<Store>();

    public Customer() {
        stores.add(new Store("Game", "1"));
        stores.add(new Store("Grocery", "2"));

        stores.get(0).addItem("001A", "GTA");
        stores.get(0).addItem("001B", "GOD OF WARS");
        stores.get(0).addItem("001C", "THE LAST OF US");

        stores.get(1).addItem("002A", "Sandwich");
        stores.get(1).addItem("002B", "Cup Noodle");
        stores.get(1).addItem("002C", "Ice Cream");
    }

    public static void main(String args[]) {
        new Customer().view();
    }

    public void view() {
        System.out.println(stores.get(0).viewItem());
    }

}

网课

class Online{
    private LinkedList<Item> items = new LinkedList<Item>();
    private String name ;
    private String number;
    public Online(String name, String number){
       this.name = name;
       this.number = number;
    }

   public static void main(String args[]){
          new Customer(“John”, “012”).view();
    }

   private void view(){
      Item item = item(“001A:GTA”);
      if(item != null)
         System.out.println(“Found”);
      else
        System.out.println(“Not found”):
   }
    public Item item(String item){
      String[] temp = item.split(":");
      String code = temp[0];
      String name = temp[1];
      for(Item item: items)
          if(item.hasItem(code, name))
             return item;
      return null;
    } 
   }
}

标签: java

解决方案


您正在搜索“001:GTA”,但在示例中您存储了项目“001A:GTA”


推荐阅读