Boolean failing to return the correct value

Tags:



I have four classes Customer, Store and Item and Online.

I am using ‘LinkedList’ to move around classes.

I added items at the Customer class.

When I want to check whether the item under exists or not under Online class.

Because you cannot check at the Customer.

I use the hasItem().It’s failing constantly.

When I say that, I mean even though I type “001A:GTA”, the item is store in the data and it’s not working. it keep returning null.

Can someone explain to me? I really appreciate it. I am a complete begineer.

Item Class

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;
    }

}

Store class

    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; 
    }
}

Customer

   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());
    }

}

Online Class

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;
    } 
   }
}

Answer

Override Object::equals

Do it as follows:

import java.util.LinkedList;
import java.util.Objects;

class Item {
    private String code, name;

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

    public String getName() {
        return name;
    }

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

    @Override
    public int hashCode() {
        return Objects.hash(name, code);
    }

    @Override
    public boolean equals(Object obj) {
        Item item = (Item) obj;
        return name.equals(item.name) && code.equals(item.code);
    }
}

class Store {
    private LinkedList<Item> items = new LinkedList<Item>();
    private String name, number;

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

    public String getName() {
        return name;
    }

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

    public LinkedList<Item> findItems() {
        return items;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Item item : items) {
            sb.append(item.toString()).append(System.lineSeparator());
        }
        return sb.toString();
    }

    public void viewStore() {
        System.out.println(name + " " + number);
    }

    /**
     * Searches the item in the store using the search string
     * 
     * @param The string combining the code and name in the format "code:name:"
     * @return Returns the matching Item. If the item is not found, null is returned
     */
    public Item findItem(String strItem) {
        String[] data = strItem.split(":");
        if (data.length < 2) {
            return null;
        }

        Item searchItem = new Item(data[0], data[1]);

        for (Item item : items) {
            if (item.equals(searchItem)) {
                return item;
            }
        }

        return null;
    }

    /**
     * Searches the item in the store using the name of the item
     * 
     * @param The name of the item
     * @return Returns the matching Item. If the item is not found, null is returned
     */
    public Item findItemByName(String itemName) {
        for (Item item : items) {
            if (item.getName().equals(itemName)) {
                return item;
            }
        }
        return null;
    }
}

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 LinkedList<Store> getStores() {
        return stores;
    }

    public void viewStore() {
        for (Store store : stores)
            store.viewStore();
    }

    public void viewItems() {
        for (Store store : stores) {
            for (Item item : store.findItems()) {
                System.out.println(item);
            }
        }
    }

    /**
     * Searches the item in all the stores related to the customer using the search
     * string
     * 
     * @param The string combining the code and name in the format "code:name:"
     * @return Returns the matching Item. If the item is not found, null is returned
     */
    public Item findItem(String strItem) {
        String[] data = strItem.split(":");
        if (data.length < 2) {
            return null;
        }

        Item searchItem = new Item(data[0], data[1]);

        for (Store store : stores) {
            for (Item item : store.findItems()) {
                if (item.equals(searchItem)) {
                    return item;
                }
            }
        }
        return null;
    }

    /**
     * Searches the item in all the stores related to the customer using the name of
     * the item
     * 
     * @param The name of the item
     * @return Returns the matching Item. If the item is not found, null is returned
     */
    public Item findItemByName(String itemName) {
        for (Store store : stores) {
            for (Item item : store.findItems()) {
                if (item.getName().equals(itemName)) {
                    return item;
                }
            }
        }
        return null;
    }
}

public class Online {
    public static void main(String[] args) {
        Item item;
        String strItem, itemName;
        Customer customer = new Customer();

        // Test searching the item using the search string in a particular store e.g.
        // first store of customer
        Store store = customer.getStores().get(0);
        System.out.println("Searching item using search string in store, " + store.getName());

        strItem = "001A:GTA";
        item = store.findItem(strItem);
        if (item == null) {
            System.out.println("Not found -> " + strItem);
        } else {
            System.out.println("Found -> " + item);
        }

        strItem = "002A:Sandwich";
        item = store.findItem(strItem);
        if (item == null) {
            System.out.println("Not found -> " + strItem);
        } else {
            System.out.println("Found -> " + item);
        }

        System.out.println();

        // Test searching the item using the search string in all the stores related to
        // the customer
        System.out.println("Searching item using search string in all the stores related to the customer");
        strItem = "001A:GTA";
        item = customer.findItem(strItem);
        if (item == null) {
            System.out.println("Not found -> " + strItem);
        } else {
            System.out.println("Found -> " + item);
        }

        strItem = "002A:Sandwich";
        item = customer.findItem(strItem);
        if (item == null) {
            System.out.println("Not found -> " + strItem);
        } else {
            System.out.println("Found -> " + item);
        }

        strItem = "ABC:XYZ";
        item = customer.findItem(strItem);
        if (item == null) {
            System.out.println("Not found -> " + strItem);
        } else {
            System.out.println("Found -> " + item);
        }

        System.out.println();

        // Test searching the item using name of the item in a particular store e.g.
        // first store of customer
        store = customer.getStores().get(0);
        System.out.println("Searching item using name of the item in store, " + store.getName());

        itemName = "GTA";
        item = store.findItemByName(itemName);
        if (item == null) {
            System.out.println("Not found -> " + strItem);
        } else {
            System.out.println("Found -> " + item);
        }

        itemName = "Sandwich";
        item = store.findItemByName(itemName);
        if (item == null) {
            System.out.println("Not found -> " + itemName);
        } else {
            System.out.println("Found -> " + item);
        }

        System.out.println();

        // Test searching the item using the name of the item in all the stores related
        // to the customer
        System.out.println("Searching item  using name of the item in all the stores related to the customer");
        itemName = "GTA";
        item = customer.findItemByName(itemName);
        if (item == null) {
            System.out.println("Not found -> " + itemName);
        } else {
            System.out.println("Found -> " + item);
        }

        itemName = "Sandwich";
        item = customer.findItemByName(itemName);
        if (item == null) {
            System.out.println("Not found -> " + itemName);
        } else {
            System.out.println("Found -> " + item);
        }

        itemName = "XYZ";
        item = customer.findItemByName(itemName);
        if (item == null) {
            System.out.println("Not found -> " + itemName);
        } else {
            System.out.println("Found -> " + item);
        }
    }
}

Output:

Searching item using search string in store, Game
Found -> GTA : 001A
Not found -> 002A:Sandwich

Searching item using search string in all the stores related to the customer
Found -> GTA : 001A
Found -> Sandwich : 002A
Not found -> ABC:XYZ

Searching item using name of the item in store, Game
Found -> GTA : 001A
Not found -> Sandwich

Searching item  using name of the item in all the stores related to the customer
Found -> GTA : 001A
Found -> Sandwich : 002A
Not found -> XYZ

Note that it doesn’t sound good for the class, Item to have a method called, hasItem. It gives an impression as if class, Item is a container class. Also, it is always a recommended practice to override Object::equals and Object::hashCode in a class. It makes your code clean (as you can see in the code given above) and helps you write logic in an easy manner; especially when you are dealing with collections.



Source: stackoverflow