Question

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

0 0
Add a comment Improve this question Transcribed image text
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
  • In this same program I need to create a new method called “int findItem(String[] shoppingList, String...

    In this same program I need to create a new method called “int findItem(String[] shoppingList, String item)” that takes an array of strings that is a shopping list and a string for an item name and searches through the “shoppingList” array for find if the “item” exists. If it does exist print a confirmation and return the item index. If the item does not exist in the array print a failure message and return -1. import java.util.Scanner; public class ShoppingList...

  • ​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...

  • A specific question I have on this project is how do I make the stars all...

    A specific question I have on this project is how do I make the stars all align into making a box. Whenever I post this question the stars on the right edge go in towards the item of the shopping list. I need the starts to create a a box around the shopping items. Instructions: Using Python write a program that allows a user to create and use a shopping list. Your program will display a menu of options to...

  • Need help with the UML for this code? Thank you. import java.util.Scanner;    public class Assignment1Duong1895...

    Need help with the UML for this code? Thank you. import java.util.Scanner;    public class Assignment1Duong1895    {        public static void header()        {            System.out.println("\tWelcome to St. Joseph's College");        }        public static void main(String[] args) {            Scanner input = new Scanner(System.in);            int d;            header();            System.out.println("Enter number of items to process");            d = input.nextInt();      ...

  • 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...

  • 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,...

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
ADVERTISEMENT