Link to home
Start Free TrialLog in
Avatar of g_currier
g_currierFlag for Germany

asked on

Selecting a specific object from a list

How do I start with this?  do i use ArrayList.contains() or something else?  How do i tell the program exactly which item to get and feed in to the cart?
Avatar of for_yan
for_yan
Flag of United States of America image

Ok, I have a meeting now - if you formulate something more concrete by that
time , we'll look at it.
Avatar of Mick Barry
depends on what you want to access it by. By index you would use list.get(index)
Avatar of g_currier

ASKER

that way however, I would have to generate more code (i.e. equating an index number to a code) wouldn't I?
You should give us more details. Tell us what you are trying to do.  
If I have to guess, then I would say that maybe you should use a Map instead of a List.  
You would use a key to get an object from your Map.

> that way however, I would have to generate more code (i.e. equating an index number to a code) wouldn't I?

you could store the index as well (or instead of the code)
Alternatively maintain a lookup for the product, mapping code to product

Map<String, Product> products

Product product = products.get(code);

allow me to upload my files:
 
package TestPackage;

/*
 * Files:
 * Item.java
 * ShoppingCart.java
 * itemList.txt (Input)
 * CartSummary.txt (Output)
 */
import java.util.*;
import java.io.*;
import javax.swing.*;


public class GoShopping {
    ArrayList shopItems;
    public GoShopping() {
        shopItems = new ArrayList();
    }

    public void shopList() throws IOException {
        //DataInputStream in = new DataInputStream(new FileInputStream("StoreItemsList.txt"));
        BufferedReader in = new BufferedReader(new FileReader("StoreItemsList.txt"));
        String buff = null;
        Item item;
        while ((buff = in.readLine()) != null) {
            StringTokenizer t = new StringTokenizer(buff, "-");
            String code = t.nextToken();
            String strPrice = t.nextToken();
            String name = t.nextToken();
            double price = Double.parseDouble(strPrice);
            int quant = 1;
            item = new Item(code, price, name, quant);
            shopItems.add(item);
        }
//        System.out.print("Code\t   Price\t Item\t\t\t\t\tQuantity\n");
//        for (int j = 0; j < shopItems.size(); j++) {
//            System.out.print((Item) shopItems.get(j));
//        }
    }
    public void selectList(){
        System.out.print("Code\t   Price\t Item\t\t\t\t\tQuantity\n");
        for (int j = 0; j < shopItems.size(); j++) {
            System.out.print(j+1+". "+(Item) shopItems.get(j));
        }
    }

    public static void main(String[] args) throws Exception {
        GoShopping go = new GoShopping();

        ShoppingCart cart = new ShoppingCart();
        Scanner input = null;
        final String INPUT_FILE = "StoreItemsList.txt";
        File inputFile = new File(INPUT_FILE);

        if (!inputFile.exists()) {
            JOptionPane.showMessageDialog(null,
                    "File '" + INPUT_FILE + "' not found. \nClick OK to end program.",
                    "File Not Found Error", JOptionPane.ERROR_MESSAGE);
            System.out.println("File '" + INPUT_FILE + "' not found.");
            System.exit(0);
        }
        Scanner scanner = new Scanner(System.in);

        // Scanner input = new Scanner(inputFile).useDelimiter("\\-");

        System.out.println("Hello! Please choose an option from the menu.\n");
        boolean isFull = false;
        int choice = 5;
        String answer = "";

        while (choice > 0) {
            displayMenu();
            choice = scanner.nextInt();
            go.shopList();
            switch (choice) {
                case 1:
                    go.selectList();
                    input = new Scanner(inputFile).useDelimiter("\\-");
                    while (input.hasNextLine()) {
                    Item buyMe = new Item();
                        String line = input.nextLine();
                        String[] lineItem = line.split("\\-");
                        String itemCode = lineItem[0];
                        String strPrice = lineItem[1];
                        String itemName = lineItem[2];

                        System.out.print("Please type in the code of the item you wish to purchase");
                        answer = scanner.next();
                        if(buyMe.getItemCode(answer)){
                            
                        }
                        if (answer.equalsIgnoreCase("Y")) {
                            int itemQuantity = 0;
                            System.out.println("How many would you like?\n");
                            itemQuantity = scanner.nextInt();
                            double itemPrice = Double.parseDouble(strPrice);
                            Item item = new Item();
                            item.setItemCode(itemCode);
                            item.setItemPrice(itemPrice);
                            item.setItemName(itemName);
                            item.setItemQuant(itemQuantity);
                            if (cart.addToCart(item)) {
                                System.out.print("Item added to your cart.\n\n");
                            } 
                        } else {
                            System.out.print("No items added");
                        }
                        // break;
                    }
                    input.close();
                    break;
                case 2:
                    System.out.print(cart.toString());
                    System.out.println("Your current bill is $" + cart.totalPrice);
                    break;
                case 3:
                    cart.EmptyCart();
                    break;
                case 4:
                    System.out.print(cart.toString());
                    System.out.println("Please pay $" + cart.totalPrice);
                    break;
                case 5:
                    input.close();
                    System.out.println("Thank you! Come again!");
                    System.exit(1);
            }
        }
    }

    public static void displayMenu() {
        System.out.println("\n-----------------------------------------");
        System.out.println("Select an Option and enter your choice.");
        System.out.println("1) Add items to your cart.");
        System.out.println("2) Display the items in your cart and the\n"
                + "   running total.");
        System.out.println("3) Empty your cart.");
        System.out.println("4) Checkout.");
        System.out.println("5) Quit");
        System.out.println("-----------------------------------------");
        System.out.print("Enter a number (1 through 5) as your choice: ");
    }
}

Open in new window

package TestPackage;

import java.util.ArrayList;


public class ShoppingCart {

    private ArrayList cart;
    private String MyCart;
    String code;
    String curCode;
    int qty1;
    int qty2;
    
    private String name;
    int currentNumberOfItems;
    double totalPrice;

    public ShoppingCart() {
        cart = new ArrayList();
        MyCart = "My Selected Items";
        totalPrice = 0.00;
        currentNumberOfItems = 0;
        code = null;
        curCode = null;
        qty1 = 0;
        qty2 = 0;
    }
    public boolean addToCart(Item newItem) {
        if (!cart.add(newItem)) {//add an item
            System.out.println("Error adding Item to cart.");
            return false;
        }
        totalPrice += newItem.getItemQuant() * newItem.getItemPrice();
        //currentNumberOfItems = newItem.getItemQuant();
        return true;
    }

    public boolean inList(Item newItem) {
        return cart.contains(newItem);
    }

    public void EmptyCart() {
        currentNumberOfItems = 0;
        totalPrice = 0.00;
        cart.clear();
    }
    public double getItemTotal(double totalPrice) {
        this.totalPrice = totalPrice;
        return totalPrice;
    }
    public void cartTrim(){
        cart.trimToSize();
    }


    @Override
    public String toString() {
        String s = "Code\t   Price\t Item\t\t\t\t\tQuantity"
                + "\n";
        //String s = "";
        for (int j = 0; j < cart.size(); j++) {
            s += cart.get(j);
        }
        return s;
    }
}

Open in new window

package TestPackage;

public class Item {
    private String itemName;
    private String itemCode;
    private int itemQuant;
    private double itemPrice;
    private int itemCapacity;



    //default constructor
    public Item(){
        itemName = null;
        itemQuant = 0;
        itemPrice = 0.00;
        itemCode = null;
        itemCapacity = 0;

    }
    //contructor with parameters
    public Item(String code,double price,String name,int quantity ){
        this.itemCode = code;
        this.itemPrice = price;
        this.itemName = name;
        this.itemQuant = quantity;
        
    }
    public Item(int itemCapacity){
        this.itemCapacity = itemCapacity;
    }

    //accessor methods
    public String getItemName(){
        return itemName;
    }

    public int getItemQuant(){
        return itemQuant;
    }

    public double getItemPrice(){
        return itemPrice;
    }

    public String getItemCode(){
        return itemCode;
    }

    public int getSize(){
        return itemCapacity;
    }
    //mutator methods
    public void setItemName(String name){
        this.itemName = name;
    }

    public void setItemQuant(int quant){
        this.itemQuant = quant;
    }

    public void setItemPrice(double price){
        this.itemPrice = price;
    }

    public void setItemCode(String code){
        this.itemCode = code;
    }

    //other methods
    @Override
    public String toString(){
        return
                getItemCode()+"\t"+
                getItemPrice()+"\t"+
                getItemName()+"\t"+
                getItemQuant()+"\n";
                

    }
}

Open in new window

package TestPackage;

import P2.Item;


public class SalesItem extends Item{

    private String code;
    private double price;
    private String name;
    private int quantity;
    private double discountRate;
    final static double discountPercentA = .25;
    final static double discountPercentB = .20;
    final static double discountPercentC = .10;


    public SalesItem(){
        code = null;
        price = 0.00;
        name = null;
        quantity = 0;
        discountRate = 0.00;
    }

    public SalesItem (String code, double price, String name, int quantity){
        super(code, price, name, quantity);
    }

    public void setCode(String code){
        super.setItemCode(code);
    }
    
    public void setDiscount(String code){
        if(super.getItemCode().startsWith("A")){
            discountRate = (price - (price*this.discountPercentA));
            super.setItemPrice(price);
        }else if(super.getItemCode().startsWith("B")){
            discountRate = (price - (price*this.discountPercentB));
            super.setItemPrice(price);
        }else if(super.getItemCode().startsWith("C")){
            discountRate = (price - (price*this.discountPercentC));
            super.setItemPrice(price);
        }
    }


    @Override
    public String toString(){
        super.toString();
        return super.toString() + " Discount: "+getItemDiscount()+"%";
    }

}

Open in new window

StoreItemsList.txt

All of this works so far.  What I have yet to do is (as stated above) allow the user to select a code from the list generated and the program resonds by adding that item (containing the item code) to the cart.  Simultaneously, the program will also determine (based on the first letter of the code) whether or not the item is eligible for a discount.  If it is, the SaleItem class overrides the item.toString() in order to append a "discount" tag to the output.  Or something along thos lines.
Unfortunately, I must walk before I can run, and I have been limited to using arrays and arraylists
then you'll need to loop through the list to find the item with the matching code
something lilke this perhaps:

 
public void selectList(String item){
        shopItems.get(shopItems.indexOf(item));
    }

Open in new window


and then using

 
answer = scanner.next();
go.selectList(answer);

Open in new window


to set it.  after that, somehow adding what the select list returns? or something...
Except that this returns an ArrayIndexOutOfBoundsException: -1...
objects has a good idea.  When you find the time look at Map. In this case, the key would be the item's code and it could point to a List with all the other stuff (price, quantity, whatever).
>         shopItems.get(shopItems.indexOf(item));

that won't work, the indexOf() would need to be passed an Item (which is what you're after)
you need a loop

for (Item item : shopItems) {
   if (item.getCode().equals(code)) {
      return item;
  }
}
So your next step will probably would be the listing of all items, and then
you ask the usee which item they want and what quantity they want.

Then you can in fact use your method addToCart - because it will check if you already have this item
and either increase quantity or add a new item - correct? It already has piece which is looking for specifed code
amonng the items in your list. In real life map will be faster but in your case probably speed is not
crucial, so the way you have it in addToCart should be OK.
Trying to make this idea work:
 
for (Item item : shopItems){
            if (item.getItemCode().equals(code))
                return item;
        }

Open in new window


but I am not so sure I can make it work.  I just read the map api and it looks interesting...
>I just read the map api and it looks interesting...  
Ok, that could be for next time. Looks like objects and for_yan can fix your current code.
thanks
this feels like it needs a method in the Item class that return everything needed to add to the cart.  I'll return to this in a few hours - I need some sleep.
this is all I could come up with and I know it is absolutley wrong...
public void selectList(String answer) {
        SalesItem sale = new SalesItem();
        ShoppingCart cart = new ShoppingCart();
        Item item = new Item();
        for (int i = 0;i <= shopItems.size();i++) {
            if (item.getItemCode().equals(answer)) {

                item.setItemCode(answer);
            }
        }
    }

Open in new window

OK. But apart from the issue of the SalesItem,
I don't see why your method which just adds to cart would not
be suitable at this time to add the item
selected by the user from the list.

With SalesItem we should think a little bit more, especially as they
require from you to create this separate class and use inheritance
(I would have done it much simpler, but if this is the requirement...)
OK, get back after you have some sleep
You probably need to read from user both code and the quantity.
So let's say code will be answer1 and quantity should be answer2.

In this way you'll add your item to the cart:

for(int j=0; j<shopItems.size(); j++) {
Item it = (Item) shopItems.get(j);
if(!it.itemCode().equals(answer))continue;
int quantt = (new Integer(answer2)).intValue();

Item it1 = new Item(it.itemCode(), it.itemPrice(), it.itemName(),quantt);

cart.addToCart(it1);

}

And addTocart will already take care of the cases
of a new type of item, vs. the one
which already exists in your cart.







I had a little time to kill.
The loop that objects suggested should look something like this.
                        answer = scanner.next();  // line 89 in GoShopping.java
                        for(int x = 0; x < go.shopItems.size(); x++){  
                             if(go.shopItems.get(x).getItemCode().equals(answer)){
                                    buyMe = go.shopItems.get(x);  
                             }
                        }

Open in new window

Please throw me a couple points when it is time to reward.  
SOLUTION
Avatar of rrz
rrz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ok, time for me to say good night. I am posting a  GoShopping.java  file that complies. Keep working.
package TestPackage;

/*
 * Files:
 * Item.java
 * ShoppingCart.java
 * itemList.txt (Input)
 * CartSummary.txt (Output)
 */
import java.util.*;
import java.io.*;
import javax.swing.*;


public class GoShopping {
    ArrayList<Item> shopItems;
    public GoShopping() {
        shopItems = new ArrayList<Item>();
    }

    public void shopList() throws IOException {
        //DataInputStream in = new DataInputStream(new FileInputStream("StoreItemsList.txt"));
        BufferedReader in = new BufferedReader(new FileReader("StoreItemsList.txt"));
        String buff = null;
        Item item;
        while ((buff = in.readLine()) != null) {
            StringTokenizer t = new StringTokenizer(buff, "-");
            String code = t.nextToken();
            String strPrice = t.nextToken();
            String name = t.nextToken();
            double price = Double.parseDouble(strPrice);
            int quant = 1;
            item = new Item(code, price, name, quant);
            shopItems.add(item);
        }
//        System.out.print("Code\t   Price\t Item\t\t\t\t\tQuantity\n");
//        for (int j = 0; j < shopItems.size(); j++) {
//            System.out.print((Item) shopItems.get(j));
//        }
    }
    public void selectList(){
        System.out.print("Code\t   Price\t Item\t\t\t\t\tQuantity\n");
        for (int j = 0; j < shopItems.size(); j++) {
            System.out.print(j+1+". "+(Item) shopItems.get(j));
        }
    }

    public static void main(String[] args) throws Exception {
        GoShopping go = new GoShopping();

        ShoppingCart cart = new ShoppingCart();
        Scanner input = null;
        final String INPUT_FILE = "StoreItemsList.txt";
        File inputFile = new File(INPUT_FILE);

        if (!inputFile.exists()) {
            JOptionPane.showMessageDialog(null,
                    "File '" + INPUT_FILE + "' not found. \nClick OK to end program.",
                    "File Not Found Error", JOptionPane.ERROR_MESSAGE);
            System.out.println("File '" + INPUT_FILE + "' not found.");
            System.exit(0);
        }
        Scanner scanner = new Scanner(System.in);

        // Scanner input = new Scanner(inputFile).useDelimiter("\\-");

        System.out.println("Hello! Please choose an option from the menu.\n");
        boolean isFull = false;
        int choice = 5;
        String answer = "";
        String itemCode;
        while (choice > 0) {
            displayMenu();
            choice = scanner.nextInt();
            go.shopList();
            switch (choice) {
                case 1:
                    go.selectList();
                    input = new Scanner(inputFile).useDelimiter("\\-");
                    while (input.hasNextLine()) {
                    Item buyMe = new Item();
                   //     String line = input.nextLine();
                   //     String[] lineItem = line.split("\\-");
                    //    String itemCode = lineItem[0];
                    //    String strPrice = lineItem[1];
                    //    String itemName = lineItem[2];
                        System.out.print("Please type in the code of the item you wish to purchase");
                        answer = scanner.next();
                        for(int x = 0; x < go.shopItems.size(); x++){  
                             if(go.shopItems.get(x).getItemCode().equals(answer)){
                                    buyMe = go.shopItems.get(x);
                                    System.out.print(buyMe.toString()); 
                             }
                        }
                        if (answer.equalsIgnoreCase("Y")) {
                            int itemQuantity = 0;
                            System.out.println("How many would you like?\n");
                            itemQuantity = scanner.nextInt();
                            //double itemPrice = Double.parseDouble(strPrice);
                           // Item item = new Item();
                           // item.setItemCode(itemCode);
                           // item.setItemPrice(itemPrice);
                          //  item.setItemName(itemName);
                          //  item.setItemQuant(itemQuantity);
                            if (cart.addToCart(buyMe)) {
                                System.out.print("Item added to your cart.\n\n");
                            } 
                        } else {
                            System.out.print("No items added");
                        }
                        // break;
                    }
                    input.close();
                    break;
                case 2:
                    System.out.print(cart.toString());
                    System.out.println("Your current bill is $" + cart.totalPrice);
                    break;
                case 3:
                    cart.EmptyCart();
                    break;
                case 4:
                    System.out.print(cart.toString());
                    System.out.println("Please pay $" + cart.totalPrice);
                    break;
                case 5:
                    input.close();
                    System.out.println("Thank you! Come again!");
                    System.exit(1);
            }
        }
    }

    public static void displayMenu() {
        System.out.println("\n-----------------------------------------");
        System.out.println("Select an Option and enter your choice.");
        System.out.println("1) Add items to your cart.");
        System.out.println("2) Display the items in your cart and the\n"
                + "   running total.");
        System.out.println("3) Empty your cart.");
        System.out.println("4) Checkout.");
        System.out.println("5) Quit");
        System.out.println("-----------------------------------------");
        System.out.print("Enter a number (1 through 5) as your choice: ");
    }
}

Open in new window

>>
>         shopItems.get(shopItems.indexOf(item));

that won't work, the indexOf() would need to be passed an Item (which is what you're after)
you need a loop

>>

It will work. As long as you have implemented Item.equals correctly. Then all you need do for a general find op is
Item itemToBeFound = shopItems.get(shopItems.indexOf(new Item(idToFind)));
if (itemToBeFound != null) {
   // Found
}

Open in new window

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for_yan,rrz,objects,cehj for the input.  I did not expect a working solution so quickly (I had actually expected more trial and error on my part).  Removing the switch was a surprise, though it looks as if it simplifies things a bit.  I am becoming more familiar with StringTokenizer and am finding that it comes in handy.  I do have to change the DataInputStream to a Buffered Reader (I can already hear the complaints I will get about it being used here).  Nevertheless, I appreciate it greatly!
Thanks for the points, but you neglected giving points to objects. He came up with the loop idea.
As for_yan implied, you should validate user input.  Maps are good. Most of time the String method split will replace StringTokenizer. Keep working.
>>.. Hbut you neglected giving points to objects. He came up with the loop idea.

A loop isn't actually necessary or desirable

>>I do have to change the DataInputStream to a Buffered Reader (I can already hear the complaints

A Scanner is usually better still
Thanks, CEHJ, you are right. We were just trying to hack out a solution for the posted code. for_yan did a lot of work and rewrote the whole thing.  for_yan didn't even use the loop.
np :)
Its ok, I don't need any points. I have a bit of an excess :)

And a loop always going to be needed if you don't use a lookup table ;)
There is an implicit loop - I have overridden equals() method
and then indexOf() worked over ArrayList - they probably do it in the loop - how else?

The main pain about this program was this inheritance with SaleslItem. Don't know maybe the idea was to use
it in a different way, but if I was not required to have this inheritance, I'd rather
add discount parameter to Item and at the expense of a few additional if's in calculations
of the price and printing toString will have the same result with much less code and,
more importantly, much less thinking and debugging.
But they need to learn inheritance....
>>
There is an implicit loop - I have overridden equals() method
and then indexOf() worked over ArrayList - they probably do it in the loop - how else?
>>

Yes, it's done in a loop - the point is in not wasting time doing it yourself ;) Also binarySearch should be used when possible (possibly not in this case)
> and then indexOf() worked over ArrayList - they probably do it in the loop - how else?

thats correct, and doing it yourself saves the mess of creating an object just to find an object
for_yan,

good work btw :)
Thanks, objects :)
Yes, the point was a practice in inheritance.  I am positive that there are much shorter ways to write this out.  Ways that I will no doubt pick up along the way if I manage to get better at doing this myself.  I am extremely grateful for the help I have received and, if it were possible, I would award more points than the limit is currently set to.  Nevertheless, I look forward to pulling my hair out even more as the next two projects will no doubt be a bit more complicated.  The last time I took this class, I managed to pass it, btu not with a high enough grade to count toward degree completion.  The vignere cipher project killed me...
Good luck. Thanks for being communicative.