Question: In Java without arrays, Create a shopping list program. Write a class called ShoppingList which allows users to add or remove items from a String
In Java without arrays,
Create a shopping list program. Write a class called ShoppingList which allows users to add or remove items from a String that you are treating as a shopping list. No arrays allowed in this program. The class ShoppingList has the following methods:
ShoppingList() - a no-args constructor that creates a new, empty ShoppingList
ShoppingList(String items) - a one arg constructor that creates a ShoppingList of the given String (items separated by commas)
String toString() - returns the current contents of the shopping list, separated by commas
void addItem(String anItem) - adds a new item to the end of the shopping list if it's not already on the list
void removeItem(String anItem) - removes an item from the shopping list (if it is on the list)
Current Code:
public class ShoppingList {
String list = "";
public ShoppingList() {
this.list += "";
}
public ShoppingList(String items) {
this.list += list;
}
public String toString() {
String temp = "";
if(this.list.contains(",")) {
temp = list.substring(0,this.list.lastIndexOf(","));
}
return temp;
}
public void addItem(String anItem) {
if(!this.list.contains(anItem)) {
this.list += anItem+",";
}
}
public void removeItem(String anItem) {
this.list.replace(anItem + ","," ");
}
Currently only works for first test but having trouble placing commas in toString, will someone help with that?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
