Question

Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list...

Assignment 1 - ITSC 2214

I have to complete the array list for a shopping list code and can't figure out how to complete it: Below is the code

  1. Complete the three empty methods (remove(), find(), and contains()) in the ShoppingListArrayList.java file. These methods are already implemented in the ShoppingListArray class.

///////////////////////////////////////////////////////////////////////////////////////////////////////////

Grocery Class (If this helps)

package Shopping;
public class Grocery implements Comparable<Grocery> {

private String name;
private String category;
private int aisle;
private float price;
private int quantity;


public Grocery(String name, String category) {
this.name = name;
this.category = category;
this.aisle = -1;
this.price = 0.0f;
this.quantity = 0;
}


public Grocery(String name, String category, int aisle, float price,
int quantity) {
this.name = name;
this.category = category;
this.aisle = aisle;
this.price = price;
this.quantity = quantity;
}

/**
* Gets the name of the item.
*
* @return the name of the item

public void setName(String name) {
this.name = name;
}


public String getCategory() {
return category;
}


public void setCategory(String category) {
this.category = category;
}
public int getAisle() {
return aisle;
}


public void setAisle(int aisle) {
this.aisle = aisle;
}
public float getPrice() {
return price;
}


public void setPrice(float price) {
this.price = price;
}


public int getQuantity() {
return quantity;
}


public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
return "Entry{" + "name=" + name + ", category=" + category
+ ", aisle=" + aisle + ", price=" + price + ", quantity="
+ quantity + '}';
}

@Override
public int compareTo(Grocery t) {
if (this.getName().toUpperCase().compareTo(t.getName().toUpperCase()) == 0) {
return this.getCategory().compareToIgnoreCase(t.getCategory().toUpperCase());
}
return this.getName().compareToIgnoreCase(t.getName().toUpperCase());
}

}

///////////////////////////////////////////////////////////////////////////////////////

shoppingListADT

///////////////////////////////////////////////////////////////////////////////////////

package Shopping;

import DataStructures.*;
public interface ShoppingListADT {
  
public void add(Grocery entry);

public boolean remove(Grocery ent);
  
public Grocery find(int index) throws IndexOutOfBoundsException,
EmptyCollectionException;
  

public int indexOf(Grocery ent) throws ElementNotFoundException;
  
public boolean contains(Grocery ent);
  

public int size();
  
public boolean isEmpty();
  
@Override
public String toString();
}
//////////////////////////////////////////////////////////////////////////////////////////////

shoppingList ArratList

package Shopping;

import DataStructures.*;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ShoppingListArrayList implements ShoppingListADT {

private ArrayList shoppingList;
public ShoppingListArrayList() {
this.shoppingList = new ArrayList<>();
}
public ShoppingListArrayList(String filename) throws FileNotFoundException {
this.shoppingList = new ArrayList<>();
scanFile(filename);
}
@Override
public void add(Grocery entry) {

// Check if this item already exists
if (this.contains(entry)) {
//Merge the quantity of new entry into existing entry
combineQuantity(entry);
return;
}

shoppingList.add(entry);
}

/**
* Method to remove an entry.
*
* @param ent to be removed
* @return true when entry was removed
* @throws DataStructures.ElementNotFoundException
*/
@Override
public boolean remove(Grocery ent) {
// the boolean found describes whether or not we find the
// entry to remove

boolean found = false;
// search in the shoppingList, if find ent in the
// list remove it, set the value of `found'


// Return false if not found
return found;
}

/**
* Method to find an entry.
*
* @param index to find
* @return the entry if found
* @throws Exceptions.EmptyCollectionException
*/
@Override
public Grocery find(int index) throws IndexOutOfBoundsException,
EmptyCollectionException {
if (this.isEmpty()) {
throw new EmptyCollectionException("ECE - find");
}
  
if(index < 0 || index > size()){
throw new IndexOutOfBoundsException("IOOBE - find");
}
  
// check whether or not the input index number is legal
// for example, < 0 or falls outside of the size
  
  
// return the corresponding entry in the shoppingList
// need to change the return value
// return null;
return shoppingList.get(index);
}

/**
* Method to locate the index of an entry.
*
* @param ent to find the index
* @return the index of the entry
* @throws ElementNotFoundException if no entry was found
*/
@Override
public int indexOf(Grocery ent) throws ElementNotFoundException {
for (int i = 0; i < shoppingList.size(); i++) {
if (shoppingList.get(i).compareTo(ent) == 0) {
return i;
}
}

throw new ElementNotFoundException("indexOf");
}

/**
* Method to determine whether the object contains an entry.
*
* @param ent to find
* @return true if and only if the entry is found
*/
@Override
public boolean contains(Grocery ent) {
boolean hasItem = false;

// go through the shoppingList and try to find the
// item in the list. If found, return true.

return hasItem;
}

/**
* Gets the size of the collection.
*
* @return the size of the collection
*/
@Override
public int size() {
return shoppingList.size();
}

/**
* Gets whether the collection is empty.
*
* @return true if and only if the collection is empty
*/
@Override
public boolean isEmpty() {
return shoppingList.isEmpty();
}

/**
* Returns a string representing this object.
*
* @return a string representation of this object
*/
@Override
public String toString() {
StringBuilder s = new StringBuilder();
s.append(String.format("%-25s", "NAME"));
s.append(String.format("%-18s", "CATEGORY"));
s.append(String.format("%-10s", "AISLE"));
s.append(String.format("%-10s", "QUANTITY"));
s.append(String.format("%-10s", "PRICE"));
s.append('\n');
s.append("------------------------------------------------------------"
+ "-------------");
s.append('\n');
for (int i = 0; i < shoppingList.size(); i++) {
s.append(String.format("%-25s", shoppingList.get(i).getName()));
s.append(String.format("%-18s", shoppingList.get(i).getCategory()));
s.append(String.format("%-10s", shoppingList.get(i).getAisle()));
s.append(String.format("%-10s", shoppingList.get(i).getQuantity()));
s.append(String.format("%-10s", shoppingList.get(i).getPrice()));
s.append('\n');
s.append("--------------------------------------------------------"
+ "-----------------");
s.append('\n');
}

return s.toString();
}

/**
* Add the quantity of a duplicate entry into the existing
*
* @param entry duplicate
*/
private void combineQuantity(Grocery entry) {
try {
int index = this.indexOf(entry);
shoppingList.get(index).setQuantity(
shoppingList.get(index).getQuantity()
+ entry.getQuantity());
} catch (ElementNotFoundException e) {
System.out.println("combineQuantity - ECE");
}

}

/**
* Scans the specified file to add items to the collection.
*
* @param filename the name of the file to scan
* @throws FileNotFoundException if the file is not found
*/
private void scanFile(String filename) throws FileNotFoundException {
Scanner scanner = new Scanner(getClass().getResourceAsStream(filename))
.useDelimiter("(,|\r\n)");

while (scanner.hasNext()) {
Grocery temp = new Grocery(scanner.next(), scanner.next(),
Integer.parseInt(scanner.next()),
Float.parseFloat(scanner.next()),
Integer.parseInt(scanner.next()));
  
add(temp);
}
}

}

Any help would be great

Homework Answers

Answer #1

Hello, I've completed the asked methods, please let me know if you need anything else. Changes are marked as bold

public class ShoppingListArrayList implements ShoppingListADT {
   private ArrayList<Grocery> shoppingList; // this arraylist must be able to store values of Grocery type.

   public ShoppingListArrayList() {
       this.shoppingList = new ArrayList<>();
   }

   public ShoppingListArrayList(String filename) throws FileNotFoundException {
       this.shoppingList = new ArrayList<>();
       scanFile(filename);
   }

   @Override
   public void add(Grocery entry) {
       // Check if this item already exists
       if (this.contains(entry)) {
           // Merge the quantity of new entry into existing entry
           combineQuantity(entry);
           return;
       }
       shoppingList.add(entry);
   }

   /**
   * Method to remove an entry.
   *
   * @param ent
   * to be removed
   * @return true when entry was removed
   * @throws DataStructures.ElementNotFoundException
   */
   @Override
   public boolean remove(Grocery ent) {
       // the boolean found describes whether or not we find the
       // entry to remove

       boolean found = false;
       // search in the shoppingList, if find ent in the
       // list remove it, set the value of `found'
       try {
           int index = this.indexOf(ent);// this will use indexOf to find index of the item passed
           shoppingList.remove(index);// this will remove the element at index, internally throws
                                       // IndexOutOfBoundsException exception
           found = true;// found is set to true, since the element was found and removed successfully
       } catch (ElementNotFoundException e) {
           System.out.println("Unable to remove as the element is not found!");
       }

       // Return false if not found
       return found;
   }

   /**
   * Method to find an entry.
   *
   * @param index
   * to find
   * @return the entry if found
   * @throws Exceptions.EmptyCollectionException
   */
   @Override
   public Grocery find(int index) throws IndexOutOfBoundsException, EmptyCollectionException {
       if (this.isEmpty()) {
           throw new EmptyCollectionException("ECE - find");
       }

       // check whether or not the input index number is legal
       // for example, < 0 or falls outside of the size
       if (index < 0 || index > this.size()) {
           throw new IndexOutOfBoundsException("IOOBE - find");
       }

       // return the corresponding entry in the shoppingList
       // need to change the return value
       // return null;
       return shoppingList.get(index);
   }

   /**
   * Method to locate the index of an entry.
   *
   * @param ent
   * to find the index
   * @return the index of the entry
   * @throws ElementNotFoundException
   * if no entry was found
   */
   @Override
   public int indexOf(Grocery ent) throws ElementNotFoundException {
       for (int i = 0; i < shoppingList.size(); i++) {
           if (shoppingList.get(i).compareTo(ent) == 0) {
               return i;
           }
       }
       throw new ElementNotFoundException("indexOf");
   }

   /**
   * Method to determine whether the object contains an entry.
   *
   * @param ent
   * to find
   * @return true if and only if the entry is found
   */
   @Override
   public boolean contains(Grocery ent) {
       boolean hasItem = false;

       // go through the shoppingList and try to find the
       // item in the list. If found, return true.
       for (Grocery item : shoppingList) {
           if (item.compareTo(ent) == 0)
               hasItem = true;
       }

       return hasItem;
   }

   /**
   * Gets the size of the collection.
   *
   * @return the size of the collection
   */
   @Override
   public int size() {
       return shoppingList.size();
   }

   /**
   * Gets whether the collection is empty.
   *
   * @return true if and only if the collection is empty
   */
   @Override
   public boolean isEmpty() {
       return shoppingList.isEmpty();
   }

   /**
   * Returns a string representing this object.
   *
   * @return a string representation of this object
   */
   @Override
   public String toString() {
       StringBuilder s = new StringBuilder();
       s.append(String.format("%-25s", "NAME"));
       s.append(String.format("%-18s", "CATEGORY"));
       s.append(String.format("%-10s", "AISLE"));
       s.append(String.format("%-10s", "QUANTITY"));
       s.append(String.format("%-10s", "PRICE"));
       s.append('\n');
       s.append("------------------------------------------------------------" + "-------------");
       s.append('\n');
       for (int i = 0; i < shoppingList.size(); i++) {
           s.append(String.format("%-25s", shoppingList.get(i).getName()));
           s.append(String.format("%-18s", shoppingList.get(i).getCategory()));
           s.append(String.format("%-10s", shoppingList.get(i).getAisle()));
           s.append(String.format("%-10s", shoppingList.get(i).getQuantity()));
           s.append(String.format("%-10s", shoppingList.get(i).getPrice()));
           s.append('\n');
           s.append("--------------------------------------------------------" + "-----------------");
           s.append('\n');
       }

       return s.toString();
   }

   /**
   * Add the quantity of a duplicate entry into the existing
   *
   * @param entry
   * duplicate
   */
   private void combineQuantity(Grocery entry) {
       try {
           int index = this.indexOf(entry);
           shoppingList.get(index).setQuantity(shoppingList.get(index).getQuantity() + entry.getQuantity());
       } catch (ElementNotFoundException e) {
           System.out.println("combineQuantity - ECE");
       }

   }

   /**
   * Scans the specified file to add items to the collection.
   *
   * @param filename
   * the name of the file to scan
   * @throws FileNotFoundException
   * if the file is not found
   */
   @SuppressWarnings("resource")
   private void scanFile(String filename) throws FileNotFoundException {
       Scanner scanner = new Scanner(getClass().getResourceAsStream(filename)).useDelimiter("(,|\r\n)");

       while (scanner.hasNext()) {
           Grocery temp = new Grocery(scanner.next(), scanner.next(), Integer.parseInt(scanner.next()),
                   Float.parseFloat(scanner.next()), Integer.parseInt(scanner.next()));

           add(temp);
       }
       scanner.close();
   }
}

screenshot:

*unable to upload the last part it is same as given in question

Know the answer?
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
Similar Questions
How do I get this portion of my List Iterator code to work? This is a...
How do I get this portion of my List Iterator code to work? This is a portion of the code in the AddressBookApp that I need to work. Currently it stops at Person not found and if it makes it to the else it gives me this Exception in thread "main" java.lang.NullPointerException    at AddressBookApp.main(AddressBookApp.java:36) iter.reset(); Person findPerson = iter.findLastname("Duck"); if (findPerson == null) System.out.println("Person not found."); else findPerson.displayEntry(); findPerson = iter.findLastname("Duck"); if (findPerson == null) { System.out.println("Person not found.");...
Task 1: You will modify the add method in the LinkedBag class.Add a second parameter to...
Task 1: You will modify the add method in the LinkedBag class.Add a second parameter to the method header that will be a boolean variable: public boolean add(T newEntry, boolean sorted) The modification to the add method will makeit possible toadd new entriesto the beginning of the list, as it does now, but also to add new entries in sorted order. The sorted parameter if set to false will result in the existing functionality being executed (it will add the...
Finish the code wherever it says TODO /**    * Node type for this list. Each...
Finish the code wherever it says TODO /**    * Node type for this list. Each node holds a maximum of nodeSize elements in an    * array. Empty slots are null.    */    private class Node {        /**        * Array of actual data elements.        */        // Unchecked warning unavoidable.        public E[] data = (E[]) new Comparable[nodeSize];        /**        * Link to next node.       ...
this is the book name. Data Structures and Abstractions with Java 1) Description: The sample programs...
this is the book name. Data Structures and Abstractions with Java 1) Description: The sample programs in Chapter 1 of your textbook are not complete. They are used for illustration purpose only. The implementation of Listing 1-1 on page 39 is explained in Chapter 2. And, in order to see the result of using it, we will need the following set of files: i. BagInteface.java – the specification only. ii. ArrayBag.java – the implementation of BagInerface.java. iii. ArrayBagDemo.java – a...
public final class SimpleRegister implements ICashRegister { //(value of coin, number of coins) private Map<Integer, Integer>...
public final class SimpleRegister implements ICashRegister { //(value of coin, number of coins) private Map<Integer, Integer> moneyBox; //store the log of transactions for auditing StringBuilder log; /** * Constructs an empty register */ public SimpleRegister() { moneyBox = new TreeMap<Integer, Integer>(); moneyBox.put(1, 0); moneyBox.put(5, 0); moneyBox.put(10, 0); moneyBox.put(25, 0); moneyBox.put(100, 0); moneyBox.put(500, 0); moneyBox.put(1000, 0); log = new StringBuilder(); } @Override public void addPennies(int num) { moneyBox.put(1, moneyBox.get(1) + num); String auditMessage = String.format("Deposit: $%.02f\n", num * 1 / 100.0f);...
I am a beginner when it comes to java codeing. Is there anyway this code can...
I am a beginner when it comes to java codeing. Is there anyway this code can be simplified for someone who isn't as advanced in coding? public class Stock { //fields private String name; private String symbol; private double price; //3 args constructor public Stock(String name, String symbol, double price) { this.name = name; this.symbol = symbol; setPrice(price); } //all getters and setters /** * * @return stock name */ public String getName() { return name; } /** * set...
Code in JAVA The requirements are as follows: The input will be in a text file...
Code in JAVA The requirements are as follows: The input will be in a text file whose name is given by arg[0] of main(). It will contain a fully-parenthesized infix expression containing only: "(", ")", "+", "-" and integers. Need help on the main and fixing the Queue. //Input: ( ( 1 + 2 ) - ( ( 3 - 4 ) + ( 7 - 2 ) ) ) ( ( 1 + 2 ) - ( 3 -...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String courseName;     private String[] students = new String[1];     private int numberOfStudents;     public COurseCom666(String courseName) {         this.courseName = courseName;     }     public String[] getStudents() {         return students;     }     public int getNumberOfStudents() {         return numberOfStudents;     }     public void addStudent(String student) {         if (numberOfStudents == students.length) {             String[] a = new String[students.length + 1];            ...
Java: ModifyStudentList.javato use anArrayListinstead of an array In StudentList.java, create two new public methods: The addStudent...
Java: ModifyStudentList.javato use anArrayListinstead of an array In StudentList.java, create two new public methods: The addStudent method should have one parameter of type Student and should add the given Student to the StudentList. The removeStudent method should have one parameter of type String. The String is the email of the student to be removed from the StudentList. In Assign5Test.java do the following: Create a new StudentList containing 3 students. Print the info of all the Students in the StudentList using...
Hello. I have an assignment that is completed minus one thing, I can't get the resize...
Hello. I have an assignment that is completed minus one thing, I can't get the resize method in Circle class to actually resize the circle in my TestCircle claass. Can someone look and fix it? I would appreciate it! If you dont mind leaving acomment either in the answer or just // in the code on what I'm doing wrong to cause it to not work. That's all I've got. Just a simple revision and edit to make the resize...