Question

Below is the code for the class shoppingList, I need to enhance it to accomplish the...

Challenge Level For the Challenge level, implement the following enhancements: • Multiple-word items • Input validation • Sin

Form One In this case, the command shall be -r n, where n is the number of the item to be removed from the list. Enter your i

Below is the code for the class shoppingList, I need to enhance it to accomplish the challenge level as stated in the description above.

public class ShoppingList {  
private java.util.Scanner scan;
private String[] list;
private int counter;

public ShoppingList() {
scan = new java.util.Scanner(System.in);
list = new String[10];
counter = 0;
}
public boolean checkDuplicate(String item) {
for(int i = 0; i < counter; i++) {
if (list[i].equals(item))
return true;
}
return false;
}
public void printList() {
System.out.println("Your shopping list:");
if(counter == 0)
System.out.println(" * No items in list.");
for(int i = 0; i < counter; i++) {
System.out.println(" " + (i + 1) + ". " + list[i]);
}   
}
public void addToList(String item) {
if(counter < 10) {
if(!checkDuplicate(item))
list[counter++] = item;
else
System.out.println("Duplicte item " + item + " not added to list.");
} else {
System.out.println("List is full. Item " + item + " not added to list.");
}
}
public void emptyList() {
list = new String[10];
System.out.println("All items removed from list.");
counter = 0;
}
public String getInput() {
System.out.print("Enter your item or command: ");
return scan.next().trim();
}
public void printWelcome() {
System.out.println("Welcome to the my Shopping List Program.");
}
public void printThankYou() {
System.out.println("Thank you for using the my Shopping List Program.");
}
public void printHelp() {
System.out.println("Here are the list of commands:");
System.out.println(" -p : Print the list");
System.out.println(" -e : Empty the list");
//System.out.println(" -r n : Remove the nth item from the list");
System.out.println(" -x : Exit the application");
System.out.println(" -h : Print this command list");
}
public void go() {
String input;
printWelcome();
printHelp();
input = getInput();
while( ! input.equals("-x")) {
switch(input) {
case "-h":
printHelp();
break;
case "-p":
printList();
break;
case "-x":
break;
case "-e":
emptyList();
break;
default:
addToList(input);
}
input = getInput();
}
printThankYou();
}
public static void main(String[] args) {
ShoppingList list;
list = new ShoppingList();
list.go();
}
}

Challenge Level For the Challenge level, implement the following enhancements: • Multiple-word items • Input validation • Single item removal The two extra-credit points for the Challenge level are allocated as follows: • one for multiple-word items, checking for blank input checking for unrecognized commands • one for single-item removal Multiple-Word Items Update this application to accept multi-word shopping list items. This will require you to update the delimiter used by the Scanner object. The useDelimiter method will allow you to change the delimiter character. You can use the newline character as the new delimiter: scan.useDelimiter("\n"); Notice that this enhancement adds additional input validation. You will need to check the input. If input isn't blank, process it as either a command or an item for the list. If the input is blank, report the error. For example: Enter your item or command: peanut butter Enter your item or command: Shopping list items cannot be blank. Note: This enhancement does not count toward Challenge points by itself, It is a necessary modification for support of removing single items from the list. Invalid Commands In the scheme that we are using, all commands start out with a hyphen. However, it is possible for the user to type an unrecognized command, for example-w. The given implementation will treat this as an item for the list, rather than as an unrecognized command. Update the driver so that, if the user types in something beginning with a hyphen that is not one of the recognized commands, print out an error message, print out the list of commands. Enter your item or command: -W Unrecognized command: -W Here are the list of commands: -p: Print the List -e : Empty the List -X: Exit -h : Print this command list Enter your item or command: Remove a single item Add a command to the menu that removes a single item from the list. There are two forms that this command could take. You may implement either form of single-item removal. Implementing both will count toward additional Challenge points.
Form One In this case, the command shall be -r n, where n is the number of the item to be removed from the list. Enter your item or command: -p Your shopping list: 1. pizza 2. milk 3. bread Enter your item or command: -r 1 Enter your item or command: -p Your shopping list: 1. milk 2. bread Form Two Alternately, the command shall be -r x, where x is the value (String) for the item to be removed from the list. Enter your item or command: -p Your shopping list: 1. milk 2. pizza 3. milk 4. bread 5. milk Enter your item or command: -r milk Enter your item or command: -P Your shopping list: 1. pizza 2. bread Notice that the String version will remove all matching occurrences of the value, if they exist. Create a method (or two) that will remove a single item from the list. For Form One, the method will take an int as its parameter, the index value of the item to be removed. For Form Two, the method will take a String as its parameter, the value of the item(s) to be removed. Any items in the list following the one removed will need to up "slide up" within the list to close the empty place. Note: It is possible that a shopping list may contains String values representing integers; for example: "3". In this case: the command -r 3 would be ambiguous. If you implement both remove options, check first for a string match, then for an index value. If the item for removal does not exist, report the error. For example, Enter your item or command: -r 15 No item 15 in shopping list Note: This command consists of two tokens. For Form One, the numerical value will need to be verified to be an integer. It will need to be checked to insure that it is in the correct range of values. If the additional token does not pass input validation, print out an error message and leave the list unchanged. Also note, as shown in the Standard level, the user list starts at one (1), not zero (0). Update the list of commands in printHelp to reflect the added command(s). You may want to add some spaces after the colon in the menu items so that the colons continue to align vertically.
0 0
Add a comment Improve this question
Answer #1

Working code implemented in Java and appropriate comments provided for better understanding:

Source code for ShoppingList.java:

/**
* The ShoppingList class enables the use of an interactive shopping
* list using a partially-filled array. This version of the class can
* only hold up to ten items.
*/
public class ShoppingList {
  
private java.util.Scanner scan;
private String[] shop;
private int index;
  
/**
* Simple constructor that instantiates the class fields
*/
public ShoppingList() {
// Used nextLine method in getInput instead of useDelimiter in constructor.
// Fixed a bug where if the first input is blank, an error message was not
// printed.
scan = new java.util.Scanner(System.in);
shop = new String[10];
index = 0;
}
  
/**
* Prints out items currently stored in the shopping list. Does
* not print out empty (null) items.
*/
public void printList() {
System.out.println("Your shopping list:");
// print the list
if (index > 0) {
for (int i = 0; i < index; i++) {
System.out.println(" " + (i+1) + ". " + shop[i]);
}
} else {
System.out.println(" * No items on list.");
}
}
  
/**
* Adds an item to the shopping list at the next available index.
* @param item The item being added to the list
*/
public void addToList(String item) {
shop[index ++] = item;
}
  
/**
* Removes every item from the list and resets the index field.
*/
public void emptyList() {
// change all values to null
for (int i = 0; i < index; i++) {
shop[i] = null;
}
index = 0;
}
  
/**
* Given an integer, removes the item at that index
* from the shopping list.
* @param num An index in the list (1-10)
*/
public void removeFromList(int num) {
// error if num is bigger than index or smaller than 1
if (num > index || num < 1) {
System.out.println(" * No item " + num + " in shopping list");
} else {
shop[num-1] = null;
  
// reorder remaining values
for (int i = num; i < index; i++) {
shop[i-1] = shop[i];
}
  
// update index field
index--;
}
}
  
/**
* Given a string, removes any equivalent items from the list. If
* the string is not found, checks if the string is numerical and calls
* the int version of the method, otherwise prints an error.
* @param item The item to be removed
*/
public void removeFromList(String item) {
int nullIndex = index;
boolean itemFound = false;
// remove item
for (int i = 0; i < index; i++) {
if (shop[i].equals(item)) {
shop[i] = null;
// user index used for nullIndex
nullIndex = i + 1;
itemFound = true;
}
}
  
// reorder remaining values
for (int i = nullIndex; i < index; i++) {
shop[i-1] = shop[i];
}
  
// update index field
if (itemFound) {
index--;
} else if (isNumeric(item)) {
removeFromList(Integer.parseInt(item));
} else {
System.out.println(" * No item " + item + " in shopping list");
}
}

/**
* Tests if a string input can be converted into an integer.
* Helper function for the removeFromList method.
* @param input User input
* @return A boolean value describing if the input is numerical
*/
private boolean isNumeric(String input) {
try {
Integer.parseInt(input);
} catch(NumberFormatException error) {
return false;
}
return true;
}
  
/**
* Tests if a given item is already in the shopping list.
* @param item The item to check
* @return a boolean value describing whether the item is in the list
*/
public boolean isDuplicate(String item) {
boolean duplicate = false;
for (String thing : shop) {
if (item.equals(thing)){
duplicate = true;
}
}
return duplicate;
}
  
/**
* Gets user input from the keyboard.
* @return The user's input
*/
public String getInput() {
System.out.print("Enter your item or command: ");
return scan.nextLine().trim();
}
  
/**
* Prints a greeting. Used when the program is started.
*/
public void printWelcome() {
System.out.println("Welcome to the XYZ Shopping List Program.");
}
  
/**
* Prints a goodbye message. Used when the program ends.
*/
public void printThankYou() {
System.out.println("Thank you for using the XYZ Shopping List Program.");
}
  
/**
* Prints a help menu that displays the supported commands of the
* shopping list.
*/
public void printHelp() {
System.out.println("Here are the list of commands:");
System.out.println(" -p : Print the list");
System.out.println(" -e : Empty the list");
System.out.println(" -r n : Remove the nth item or the item " +
"n from the list");
System.out.println(" -x : Exit the application");
System.out.println(" -h : Print this command list");
}
  
/**
* The driver method of the class. This method is responsible for all
* program-user interactions.
*/
public void go() {
String input;
  
printWelcome();
printHelp();
input = getInput();
while( ! input.equals("-x")) {
switch(input) {
case "":
System.out.println("Shopping list items cannot be blank.");
break;
case "-h":
printHelp();
break;
case "-p":
printList();
break;
case "-x":
break;
case "-e":
emptyList();
break;
default:
// case "-r n"
if (input.startsWith("-r ") && input.length() > 3) {
String subInput = input.substring(3, input.length());
removeFromList(subInput);
  
// identify unknown commands
} else if (input.startsWith("-")) {
System.out.println("Unrecognized command: " + input);
printHelp();
  
// identify duplicates
} else if (isDuplicate(input)) {
System.out.println("Duplicate item " + input +
" not added to the list.");
  
// check if list is full
} else if (index > 9) {
System.out.println("List is full. Item " + input +
" not added to the list.");
  
// if tests pass, add input to list
} else {
addToList(input);
}
}
input = getInput();
}
printThankYou();
}
  
/**
* The application method. Calls the driver function to start the program.
* @param args The command line arguments
*/
public static void main(String[] args) {
ShoppingList list;
  
list = new ShoppingList();
list.go();
}
}

Sample Output Screenshots:

Hope it helps, if you like the answer give it a thumbs up. Thank you.

Add a comment
Know the answer?
Add Answer to:
Below is the code for the class shoppingList, I need to enhance it to accomplish the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • ​I have to create two classes one class that accepts an object, stores the object in...

    ​I have to create two classes one class that accepts an object, stores the object in an array. I have another that has a constructor that creates an object. Here is my first class named "ShoppingList": import java.util.*; public class ShoppingList {    private ShoppingItem [] list;    private int amtItems = 0;       public ShoppingList()    {       list=new ShoppingItem[8];    }       public void add(ShoppingItem item)    {       if(amtItems<8)       {          list[amtItems] = ShoppingItem(item);...

  • Q1 (2 pts) Shopping list Write a program that prompts a user for items on their...

    Q1 (2 pts) Shopping list Write a program that prompts a user for items on their shopping list and keeps prompting the user until they enter "Done" (make sure your program can stop even if the user enters "Done" with different cases, like "done"), then prints out the items in the list, line by line, and prints the total number of items on the shopping list. Output (after collecting items in the while loop) should look something like this: Apple...

  • Grocery shopping list (LinkedList)

    Given a ListItem class, complete main() using the built-in LinkedList type to create a linked list called shoppingList. The program should read items from input (ending with -1), adding each item to shoppingList, and output each item in shoppingList using the printNodeData() method.Ex. If the input is:the output is:--ShoppingList.java:import java.util.Scanner;import java.util.LinkedList;public class ShoppingList {   public static void main (String[] args) {      Scanner scnr = new Scanner(System.in);      // TODO: Declare a LinkedList called shoppingList of type ListItem      String...

  • Grocery shopping list (LinkedList)

    Given a ListItem class, complete main() using the built-in LinkedList type to create a linked list called shoppingList. The program should read items from input (ending with -1), adding each item to shoppingList, and output each item in shoppingList using the printNodeData() method.Ex. If the input is:the output is:--ShoppingList.java:import java.util.Scanner;import java.util.LinkedList;public class ShoppingList {   public static void main (String[] args) {      Scanner scnr = new Scanner(System.in);      // TODO: Declare a LinkedList called shoppingList of type ListItem      String...

  • Need three seperate files. ShoppingCartManager.java ShoppingCart.java ItemsToPurchase.java These are from part 1 what do you mean...

    Need three seperate files. ShoppingCartManager.java ShoppingCart.java ItemsToPurchase.java These are from part 1 what do you mean by deep study 7.25 LAB*: Program: Online shopping cart (Part 2) Note: Creating multiple Scanner objects for the same input stream yields unexpected behavior. Thus, good practice is to use a single Scanner object for reading input from System.in. That Scanner object can be passed as an argument to any methods that read input This program extends the earlier Online shopping cart program (Consider...

  • Zybooks 11.12 LAB*: Program: Online shopping cart (continued) Python 3 is the code needed and this...

    Zybooks 11.12 LAB*: Program: Online shopping cart (continued) Python 3 is the code needed and this is in Zybooks Existing Code # Type code for classes here class ItemToPurchase: def __init__(self, item_name="none", item_price=0, item_quantity=0): self.item_name = item_name self.item_price = item_price self.item_quantity = item_quantity # def __mul__(self): # print_item_cost = (self.item_quantity * self.item_price) # return '{} {} @ ${} = ${}' .format(self_item_name, self.item_quantity, self.item_price, print_item_cost) def print_item_cost(self): self.print_cost = (self.item_quantity * self.item_price) print(('{} {} @ ${} = ${}') .format(self.item_name, self.item_quantity, self.item_price,...

  • Online shopping cart (continued) (Java) Hello, I need help with Java to figure this out. In...

    Online shopping cart (continued) (Java) Hello, I need help with Java to figure this out. In my Shopping Cart Manager Class (Bottom Code), I get "Resource leak: 'sc' is never closed." I have tried multiple things and cannot figure it out. Thank you. Online shopping cart (continued) (Java) Hello, I need help with Java to figure this out. In my Shopping Cart Manager Class (Bottom Code), I get "Resource leak: 'sc' is never closed." I have tried multiple things and...

  • This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program).

    Ch 7 Program: Online shopping cart (continued) (Java)This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program).(1) Extend the ItemToPurchase class per the following specifications:Private fieldsstring itemDescription - Initialized in default constructor to "none"Parameterized constructor to assign item name, item description, item price, and item quantity (default values of 0). (1 pt)Public member methodssetDescription() mutator & getDescription() accessor (2 pts)printItemCost() - Outputs the item name followed by the quantity, price, and subtotalprintItemDescription() - Outputs the...

  • (How do I remove the STATIC ArrayList from the public class Accounts, and move it to...

    (How do I remove the STATIC ArrayList from the public class Accounts, and move it to the MAIN?) import java.util.ArrayList; import java.util.Scanner; public class Accounts { static ArrayList<String> accounts = new ArrayList<>(); static Scanner scanner = new Scanner(System.in);    public static void main(String[] args) { Scanner scanner = new Scanner(System.in);    int option = 0; do { System.out.println("0->quit\n1->add\n2->overwirte\n3->remove\n4->display"); System.out.println("Enter your option"); option = scanner.nextInt(); if (option == 0) { break; } else if (option == 1) { add(); } else...

  • Write in c++ please Imagine you are writing a program to manage a shopping list. Each...

    Write in c++ please Imagine you are writing a program to manage a shopping list. Each shopping list item is represented by a string stored in a container. Your design requires a print function that prints out the contents of the shopping list Using a vector to hold the shopping list items, write a print function to print out the contents of a vector of strings. Test your print function with a main program that does the following: 1. Create...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT