I am trying to find and remove an element from my ArrayList list
(made from a custom master class ShoppingBasket
) based on a user inputted String itemSearch
whereby they would enter say Apple
if they wanted to remove that from the basket, regardless of if the quantity is higher than 1.
The project is setup so that I have a masterclass ShoppingCart
, with several subclasses Fruit
, Dairy
. Each class has a itemName
and itemQuantity
attribute.
Here is my Fruit
class:
public class Fruit extends ShoppingBasket {
Fruit(String itemName, int itemQuantity){
super(itemName, itemQuantity);
}
}
Here is my Dairy
sub-class code:
public class Dairy extends ShoppingBasket{
Dairy(String itemName, int itemQuantity){
super(itemName, itemQuantity);
}
}
For my ShoppingCard
class I have hard-coded examples of instances of the Fruit
and Diary
classes and added them to a list to use as test data. I then try to iterate through that list and check each item against the name of the item the user has inputted and when it has found the correct item I try to remove it and print out the result. However, when it goes to print out the result, the program has not removed the item. When Debugging and using a Stop point
I notice the program does not enter the if statement.
Below is the code for the master ShoppingBasket
class:
import java.util.*;
import javax.swing.plaf.basic.BasicComboBoxUI.ItemHandler;
public class ShoppingBasket {
public String itemName;
public int itemQuantity;
static String itemSearch;
ShoppingBasket(String itemName, int itemQuantity){
this.itemName = itemName;
this.itemQuantity = itemQuantity;
}
public static void main(String[] args) {
List<ShoppingBasket> list = new ArrayList<ShoppingBasket>();
list.add(new Fruit("Apple", 2));
list.add(new Fruit("Orange", 4));
list.add(new Dairy("Semi-Skimmed Milk", 1));
list.add(new Dairy("Full Fat Milk", 3));
Scanner scnr = new Scanner(System.in);
System.out.println("What is the item that you want to remove from your basket? ");
itemSearch = scnr.nextLine();
for(ShoppingBasket s: list){
if(s.getItemName() != null && s.getItemName().contains(itemSearch)){
list.remove(itemSearch);
}
}
System.out.println(list.toString());
}
public String toString() {
return "Item name: " + this.itemName + " | Quantity: " + this.itemQuantity;
}
public String getItemName(){
return itemName;
}
}
Any help or hints of where I am going wrong would be appreciated. I apologise if this code is messy, I am new and trying to grasp the basics like Super Class
and Sub Classes
as well as other concepts of Java.