Solved

using user input to determine if discount is applicable

Posted on 2011-02-16
56
289 Views
Last Modified: 2012-05-11
GoShopping.java
 ShoppingCart.java
 Item.java
 SalesItem.java

The above files are slightly revised from those yesterday, with the addition of the SalesItem.java class (As per instructions).  The SalesItem class is basic and undeveloped.  I need to first be able to accept user input for the item code while the program has to recognize the code and input the appropriate item.

step 1.  
create a way to display the item list

step 2.
create a way for the program to accept user input for each item

step 3.
create a way for the program to recognize the code and insert the corresponding item

if you have ideas, that would be great.  I will try to muddle through how to do it in the meantime.
0
Comment
Question by:g_currier
  • 30
  • 22
  • 4
56 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 34908848
So you mean that you'll first silently read in the whole list
and ask user for the code of the item from that list, rather than reading
sequentially hrough the list and asking about each item?

That would sound more reasonable behavior to me and also easier to program
0
 

Author Comment

by:g_currier
ID: 34909660
That's what I believe the instructions indicate (at least, according to the output example in the pdf)
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34909711
Then just read everything and make another ArrayList of items existing in the shop
and then compare the item code with the user input and then build in such a way cart
which will be independent ArrayList in the cart - seems logical - and reading
from the file in one shot - will be simpler logically

0
 

Author Comment

by:g_currier
ID: 34909731
Check the GoShopping class I posted here...it's a good start I think but I am having problems getting it to display properly
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34909799
But it is broken - when I just use option 1 to add - it imeedaitely reposrt an error.
Do you have the version which works?
 
0
 

Author Comment

by:g_currier
ID: 34909807
not yet...I'm still trying to figure out how to feed the arraylist using the delimiter...or shoudl I just use a string array?
0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 500 total points
ID: 34909890
Well, that depends on the habit
I use to do it like that :

DataInputStream in = new DataInputStream(new FileInputStream("filename.txt"));

String buff = null;

while((buff=in.readLine()) != null){
StringTokenizer t = new StringTokenizer(buff," ");
String s1 = t.nextToken();
String s2 = t.nextToken();
etc..

}

Good old way -without all these scnners and splitters
and in the contructor of StringTokenizer you can
put any number of separators as you want, say
this new StringTokenizer(buff,", /-") will treat
any of the comma, space, slash and dash as separators

Then you read the line - analyze all pieces
use constructor to create your Item
and just add it to ArrayList
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 34909902
You will need to hold 'listArray' as an instance variable.

Don't fall into the trap of placing too much code in main or you'll find it quickly becomes unmanageable
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 34909929
After carrying out my first suggestion, all you need to do to print the items is
for(Item i : listArray) {
    System.out.println(i);
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 34909930
So every pass through this while loop you will be reading one line,
when buff becomse null - that will mean end of file,
and it'll get you out of the while loop, then you close your stream with
 in.close()

The compiler will write that in.readLine() is deprecated - don't pay attention -
no one invented anything better than that since the sliced bread anyway - and it works absolutely
on all Java implementations
0
 

Author Comment

by:g_currier
ID: 34909994
OK, i'll give it a try and post my results
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34910014

Yes, no question, to put this lot of code in main is really a bad thing.

For now you can just move all your code to constructior
public GoShopping(){
all your code
}

and in main just leave one line
....main(..){
new GoShopping();
}
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34910038
In general it would be nicer to leave the reading of the file in the constructor
and move the proces of interaction with user to a separate method,
but all those changes should be done absolutely stepwise - after each change
checking if it is still working.
0
 

Author Comment

by:g_currier
ID: 34910039
like:
public static GoShopping(){
}
?

the same way as the displayMenu() correct?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34910054
No static for constructor; just punblic GoShopping() {...}
0
 

Author Comment

by:g_currier
ID: 34910068
ok, working on it
0
 

Author Comment

by:g_currier
ID: 34910252
OK, it's all written out.  problem with the loop though:
I delcared listArray as instance variable,
I get an error (for the loop) syaing incompatible types, Item expected, found Object
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 34910278
Please post code used in loop
0
 

Author Comment

by:g_currier
ID: 34910287
for (Item i : listArray) {
            System.out.println(i);
        }
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34910296
post your code and indicate the line which reports the error
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34910334
System.out.println((Item)i)
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34910360
I use again the old way:

for (int j=0; j<listArray.size(); j++){
System.out.println((Item)listArray.get(i);
}

longer, but realiably
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34910382
Did you add Item's to your list Array?
say listArray.add(new Item(...))  ?
0
 

Author Comment

by:g_currier
ID: 34910394
Had to add the IOException or I would have had to start adding try-catch blocks
public GoShopping() throws IOException {
        Item item = new Item();
        DataInputStream in = new DataInputStream(new FileInputStream("StoreItemsList.txt"));
        String buff = null;

        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);
            item.setItemCode(code);
            item.setItemPrice(price);
            item.setItemName(name);
            String dispList = item.toString();
            listArray = new ArrayList();
            listArray.add(dispList);


        }
        for (int j = 0; j < listArray.size(); j++) {
            System.out.println((Item) listArray.get(j));
        }
        in.close();
        }

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 34910395
You should be declaring an Item List (e.g. as below) and then adding your Item instances to it
private List<Item> items = new ArrayList<Item>();

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 34910438
Look, you are addin not items but list to your list Array
0
 

Author Comment

by:g_currier
ID: 34910439
one thing first...
I add "new GoShopping();" and it's telling me instance ignored.   I allow NetBeans to  "fix it and It add the line GoShopping goShopping = new GoShopping();

I then add the line goShopping(); to case 1 and the compiler doesn't like it...
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34910444
or you are adding strings - don't do that
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 47

Expert Comment

by:for_yan
ID: 34910452
and you cannot create listArray within the loop - this is
something which you crete before and then jkaust add items to it
0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
ID: 34910463
smth like that:  
ArrayList  listArray = new AraryList();

   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);
            item.setItemCode(code);
            item.setItemPrice(price);
            item.setItemName(name);
                      listArray.add(item);
           


        }
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34910484
better not to name your variables in such way listArray - confusing
with ArrayList and this is your main repository - call it
something list  productList or somthing - don't change already now - but for futue
0
 

Author Comment

by:g_currier
ID: 34910555
More like this?
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.lang.*;

public class GoShopping {
    
private Item item = new Item();
ArrayList listArray;

    public GoShopping() throws IOException {
        
        DataInputStream in = new DataInputStream(new FileInputStream("StoreItemsList.txt"));
        String buff = null;
        List<Item> itemList = new ArrayList<Item>();
        //listArray = new ArrayList();
        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.setItemCode(code);
            item.setItemPrice(price);
            item.setItemName(name);
            item.setItemQuant(quant);
            itemList.add(item);
        }
        for (int j = 0; j < itemList.size(); j++) {
            System.out.println((Item) itemList.get(j));
        }
        in.close();
    }

Open in new window


0
 

Author Comment

by:g_currier
ID: 34910594
and the contructor problem? Should I change the name of the method or something?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34910680
Yes, more or less like that
Constructor name is OK
I usually don't throw exception in the constructor but rather catch them in the
try ... catch loop,
but it does not mean that I am doing it in the best way, if compiler is fine with it,
then OK.
So does it work?
0
 

Author Comment

by:g_currier
ID: 34910767
no.  if I leave it as public getShopList(){...} (note the name change) i get this problem:
invalid method declaration; return type required

if I add a return value, I get this:
cannot return a value from method whose result type is void

When I change it to public void getShopList() throws IOException {...}
I get this when trying to instantiate in case 1 "new getShopList();"

non-static method getShopList() cannot be referenced from a static context
and it wants to create a private static class with a new public method within which I get the same problem as I started with.

What am I doing wrong?
/*
 * Files:
 * Item.java
 * ShoppingCart.java
 * itemList.txt (Input)
 * CartSummary.txt (Output)
 *
 */
package TestPackage;

import java.util.*;
import java.io.*;
import javax.swing.*;
import java.lang.*;

public class GoShopping {

    private Item item = new Item();
    ArrayList productList;

    public static void main(String[] args) throws Exception {

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

        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;
        int count = 0;
        String answer = "";

        while (choice > 0) {
            displayMenu();
            choice = scanner.nextInt();
            input = new Scanner(inputFile).useDelimiter("\\-");
            switch (choice) {
                case 1:

                    while (input.hasNextLine()) {

                        String line = input.nextLine();
                        String[] lineItem = line.split("\\-");
                        String itemCode = lineItem[0];
                        String strPrice = lineItem[1];
                        String itemName = lineItem[2];

                        System.out.print("Add item code " + lineItem[0] + ",\"" + lineItem[2] + "\"to your cart?\n"
                                + "Type \"Y\" for Yes or \"N\" for No.\n");

                        answer = scanner.next();
                        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("Item not added.\n\n");

                            }
                        } else {
                            System.out.print("No items added");

                        }
                    }
                    input.close();
                    break;
                case 2:
                    System.out.print(cart.toString() + "\n"
                            + "Running total: " + cart.totalPrice);

                    break;
                case 3:
                    cart.EmptyCart();
                    break;
                case 4:
                    //output to screen and file anf finalize the list with the trim function
                    System.out.print(cart.toString() + "\n"
                            + "Please Pay: " + cart.totalPrice);
                    cart.cartTrim();
                    break;
                case 5:
                    input.close();
                    System.out.println("Thank you! Come again!");
                    System.exit(0);
            }
        }
    }

    public getShopList() throws IOException {

        DataInputStream in = new DataInputStream(new FileInputStream("StoreItemsList.txt"));
        String buff = null;
        List<Item> shopItems = new ArrayList<Item>();
        //listArray = new ArrayList();
        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.setItemCode(code);
            item.setItemPrice(price);
            item.setItemName(name);
            item.setItemQuant(quant);
            shopItems.add(item);
        }
        String s = "";
        for (int j = 0; j < shopItems.size(); j++) {
            System.out.println((Item) shopItems.get(j));
        }
        in.close();

    }

    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

0
 
LVL 47

Expert Comment

by:for_yan
ID: 34910839
because all methods with the exception of constructor (which
would have the same name as a class, and that how compiler knows it)
all other methods should have a return type in decalarion or "void" if the method
returns niothing. If in this method you just accumulate the list and print it thenyou may not need the retur value - then you say
public void getShoppingList()
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34910860
However if your goal is to accumulate info annd put it into the list and
not return the list itself friom the method, then your list dhould
be declared not within the method, but outside it - as
an instance variable - in this way you'll still preserve the value of
your list to use it in other pieces of the class
0
 

Author Comment

by:g_currier
ID: 34910895
"non-static method getShopList() cannot be referenced from a static context"

is what I get when adding the line:
getShopList();
using the code below

main method is static (standard I think) so it won't work in here.  would it work if I dropped it into the say "Item" class?
public void getShopList() throws IOException {
        DataInputStream in = new DataInputStream(new FileInputStream("StoreItemsList.txt"));
        String buff = null;
        List<Item> shopItems = new ArrayList<Item>();
        //listArray = new ArrayList();
        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.setItemCode(code);
            item.setItemPrice(price);
            item.setItemName(name);
            item.setItemQuant(quant);
            shopItems.add(item);
        }
        String s = "";
        for (int j = 0; j < shopItems.size(); j++) {
            s+= (Item)shopItems.get(j);
//            System.out.println((Item) shopItems.get(j));
        }
        in.close();
        System.out.println(s);
    }

Open in new window

0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 500 total points
ID: 34910905
so there are basically two possible ways, either
you declare your ArrayList outside methods as instant variable


ArrayList myList = new ArryList();

public void getList(){
put some data in the list,
then call anothe method for exmaple
}

public void anotherMethos() {
read the list - theat would have inforation aslist is part of the instance

}



Alternatvivwely you need to return the list, then

public ArrayList getShopList() {
ArrayList aa = new ArrayList();

populate data reading file, etc.

return aa;
}

and then you call this method from another
place in your class like that:

ArrayList bb = getShopList();

That's what is necessary to understand



0
 

Author Comment

by:g_currier
ID: 34910926
This is where my biggest problem lies - with constructors, inheritance, etc. , so please be patient as I try to get it...and I really appreciate your help.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34910936
You cannot mix these tow wvariants - like haveing void method and creating list inside that method -
what will be the uise of that? The data which you stored in your list will be lost as soon
as you leva your method - understood?

As I told you - in main you just leave one operator -
 new GoShopping()
Everything else move to the constructor - then you'll not need to call non-staitic methods (most of the methods
are non-static usualy) from main
0
 

Author Comment

by:g_currier
ID: 34911066
OK Well, it displays something now...just the last item in the input file. That's a start at least.
/* Files:
 * Item.java
 * ShoppingCart.java
 * itemList.txt (Input)
 * CartSummary.txt (Output)
 */
package TestPackage;

import java.util.*;
import java.io.*;
import javax.swing.*;

public class GoShopping {
    private Item item = new Item();
    ArrayList shopItems = new ArrayList();
    //List<Item> shopItems = new ArrayList<Item>();

    public static void main(String[] args) throws Exception {

        ShoppingCart cart = new ShoppingCart();
        final String INPUT_FILE = "StoreItemsList.txt";
        Scanner input = null;
        Scanner scanner = null;
        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);
        }
        System.out.println("Hello! Please choose an option from the menu.\n");
        scanner = new Scanner(System.in);
        input = new Scanner(inputFile).useDelimiter("\\-");
        int choice = 5;
        String answer = "";
        
        while (choice > 0) {
            displayMenu();
            choice = scanner.nextInt();
            GoShopping shop = new GoShopping();
            
            
            switch (choice) {
                case 1:
                    shop.shopList();
                    while (input.hasNextLine()) {
                        String line = input.nextLine();
                        String[] lineItem = line.split("\\-");
                        String itemCode = lineItem[0];
                        String strPrice = lineItem[1];
                        String itemName = lineItem[2];
                        System.out.print("Add item code " + lineItem[0] + ",\"" + lineItem[2] + "\"to your cart?\n"
                                + "Type \"Y\" for Yes or \"N\" for No.\n");
                        answer = scanner.next();
                        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("Item not added.\n\n");

                            }
                        } else {
                            System.out.print("No items added");
                            
                        }
                    }
                    input.close();
                    break;
                case 2:
                    System.out.print(cart.toString() + "\n"
                            + "Running total: " + cart.totalPrice);
                     break;
                case 3:
                    cart.EmptyCart();
                    break;
                case 4:
                    //output to screen and file anf finalize the list with the trim function
                    System.out.print(cart.toString() + "\n"
                            + "Please Pay: " + cart.totalPrice);
                    cart.cartTrim();
                    break;
                case 5:
                    input.close();
                    System.out.println("Thank you! Come again!");
                    System.exit(0);
            }
        }
    }

    public void shopList() throws IOException {
        DataInputStream in = new DataInputStream(new FileInputStream("StoreItemsList.txt"));
        String buff = null;
        //listArray = new ArrayList();
        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.setItemCode(code);
            item.setItemPrice(price);
            item.setItemName(name);
            //item.setItemQuant(quant);
            shopItems.add(item);
        }
        for (int j = 0; j < shopItems.size(); j++) {
            System.out.println((Item) shopItems.get(j));
        }
    }

    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

0
 
LVL 47

Expert Comment

by:for_yan
ID: 34911136
No, why in the mioddle you write  GoShopping shop = new GoShopping();

You rather remove it, move all your code into constructor
public GoShopping(){
here all you code
}

and in main just one line

...main(...) {
new GoShopping();
}
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34911177
Then your instancwe varaibles should be just declared outside everything

like that and then actually creted inside constructor

ArrayList shopItems;


public GoShopping() {

shopItems = new ArrayList();
....

}

You should probably look at least at one example
of small java program - those things are ll very logical
easy to rememeber once you understand them

0
 

Author Comment

by:g_currier
ID: 34911190
there has to be something I missed.  this is the code, altered as you instructed.
/* Files:
 * Item.java
 * ShoppingCart.java
 * itemList.txt (Input)
 * CartSummary.txt (Output)
 */
package TestPackage;

import java.util.*;
import java.io.*;
import javax.swing.*;

public class GoShopping {
    private Item item = new Item();
    ArrayList shopItems = new ArrayList();
    //List<Item> shopItems = new ArrayList<Item>();
public GoShopping()throws IOException{
    //public void shopList() throws IOException {
        DataInputStream in = new DataInputStream(new FileInputStream("StoreItemsList.txt"));
        String buff = null;
        //listArray = new ArrayList();
        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.setItemCode(code);
            item.setItemPrice(price);
            item.setItemName(name);
            item.setItemQuant(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 static void main(String[] args) throws Exception {
    new GoShopping();
        ShoppingCart cart = new ShoppingCart();
        final String INPUT_FILE = "StoreItemsList.txt";
        Scanner input = null;
        Scanner scanner = null;
        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);
        }
        System.out.println("Hello! Please choose an option from the menu.\n");
        scanner = new Scanner(System.in);
        input = new Scanner(inputFile).useDelimiter("\\-");
        int choice = 5;
        String answer = "";
        
        while (choice > 0) {
            displayMenu();
            choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    shopList();
                    while (input.hasNextLine()) {
                        String line = input.nextLine();
                        String[] lineItem = line.split("\\-");
                        String itemCode = lineItem[0];
                        String strPrice = lineItem[1];
                        String itemName = lineItem[2];
                        System.out.print("Add item code " + lineItem[0] + ",\"" + lineItem[2] + "\"to your cart?\n"
                                + "Type \"Y\" for Yes or \"N\" for No.\n");
                        answer = scanner.next();
                        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("Item not added.\n\n");

                            }
                        } else {
                            System.out.print("No items added");

                        }
                    }
                    input.close();
                    break;
                case 2:
                    System.out.print(cart.toString() + "\n"
                            + "Running total: " + cart.totalPrice);
                     break;
                case 3:
                    cart.EmptyCart();
                    break;
                case 4:
                    //output to screen and file anf finalize the list with the trim function
                    System.out.print(cart.toString() + "\n"
                            + "Please Pay: " + cart.totalPrice);
                    cart.cartTrim();
                    break;
                case 5:
                    input.close();
                    System.out.println("Thank you! Come again!");
                    System.exit(0);
            }
        }
    }



    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

0
 

Author Comment

by:g_currier
ID: 34911204
quick change...
/* Files:
 * Item.java
 * ShoppingCart.java
 * itemList.txt (Input)
 * CartSummary.txt (Output)
 */
package TestPackage;

import java.util.*;
import java.io.*;
import javax.swing.*;

public class GoShopping {
    private Item item = new Item();
    ArrayList shopItems;
    //List<Item> shopItems = new ArrayList<Item>();
public GoShopping()throws IOException{
    shopItems = new ArrayList();
    //public void shopList() throws IOException {
        DataInputStream in = new DataInputStream(new FileInputStream("StoreItemsList.txt"));
        String buff = null;
        //listArray = new ArrayList();
        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.setItemCode(code);
            item.setItemPrice(price);
            item.setItemName(name);
            item.setItemQuant(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 static void main(String[] args) throws Exception {
    new GoShopping();
        ShoppingCart cart = new ShoppingCart();
        final String INPUT_FILE = "StoreItemsList.txt";
        Scanner input = null;
        Scanner scanner = null;
        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);
        }
        System.out.println("Hello! Please choose an option from the menu.\n");
        scanner = new Scanner(System.in);
        input = new Scanner(inputFile).useDelimiter("\\-");
        int choice = 5;
        String answer = "";
        
        while (choice > 0) {
            displayMenu();
            choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    shopList();
                    while (input.hasNextLine()) {
                        String line = input.nextLine();
                        String[] lineItem = line.split("\\-");
                        String itemCode = lineItem[0];
                        String strPrice = lineItem[1];
                        String itemName = lineItem[2];
                        System.out.print("Add item code " + lineItem[0] + ",\"" + lineItem[2] + "\"to your cart?\n"
                                + "Type \"Y\" for Yes or \"N\" for No.\n");
                        answer = scanner.next();
                        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("Item not added.\n\n");

                            }
                        } else {
                            System.out.print("No items added");

                        }
                    }
                    input.close();
                    break;
                case 2:
                    System.out.print(cart.toString() + "\n"
                            + "Running total: " + cart.totalPrice);
                     break;
                case 3:
                    cart.EmptyCart();
                    break;
                case 4:
                    //output to screen and file anf finalize the list with the trim function
                    System.out.print(cart.toString() + "\n"
                            + "Please Pay: " + cart.totalPrice);
                    cart.cartTrim();
                    break;
                case 5:
                    input.close();
                    System.out.println("Thank you! Come again!");
                    System.exit(0);
            }
        }
    }



    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

0
 
LVL 47

Expert Comment

by:for_yan
ID: 34911224
That is how it works - it is very simple

public class MyClass {
float f;
int i;
ArrayList myList;  <---  instance variables


public MyClass() {  <--- contsructor
i=5;
myList = new ArrayList();


}

public void getList() {  <---regular method

populate list here
return myList;
}


public static void main(String [] args){ <--- your main method
new MyClass();
}


}

look at some ocde somewhere -
0
 

Author Comment

by:g_currier
ID: 34911413
Ok, this is exactly the way you have demonstrated and I get it with the constructor, its the exactly the same in Item and ShoppingCart, so I understand.  The problem is, it still doesn't do as needed.  So instead of offering my own explanation, I invite you to run the code that I post here.
Again, the pattern is exactly as you have described and it makes sense because I've done that before with the other two - create default construcotrs then create parameterized constructors for data input.  So please have a look and run my code because I am not seeing the problem as clearly as you are.
/* Files:
 * Item.java
 * ShoppingCart.java
 * itemList.txt (Input)
 * CartSummary.txt (Output)
 */
package TestPackage;

import java.util.*;
import java.io.*;
import javax.swing.*;

public class GoShopping {

    Item item;
    ArrayList shopItems;
    //List<Item> shopItems = new ArrayList<Item>();

    public GoShopping() {
        item = new Item();
        shopItems = new ArrayList();
    }

    public void shopList() throws IOException {
        DataInputStream in = new DataInputStream(new FileInputStream("StoreItemsList.txt"));
        String buff = null;
        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.setItemCode(code);
            item.setItemPrice(price);
            item.setItemName(name);
            item.setItemQuant(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 static void main(String[] args) throws Exception {
        new GoShopping();
        ShoppingCart cart = new ShoppingCart();
        final String INPUT_FILE = "StoreItemsList.txt";
        Scanner input = null;
        Scanner scanner = null;
        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);
        }
        System.out.println("Hello! Please choose an option from the menu.\n");
        scanner = new Scanner(System.in);
        input = new Scanner(inputFile).useDelimiter("\\-");
        int choice = 5;
        String answer = "";

        while (choice > 0) {
            displayMenu();
            choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    shopList();
                    while (input.hasNextLine()) {
                        String line = input.nextLine();
                        String[] lineItem = line.split("\\-");
                        String itemCode = lineItem[0];
                        String strPrice = lineItem[1];
                        String itemName = lineItem[2];
                        System.out.print("Add item code " + lineItem[0] + ",\"" + lineItem[2] + "\"to your cart?\n"
                                + "Type \"Y\" for Yes or \"N\" for No.\n");
                        answer = scanner.next();
                        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("Item not added.\n\n");

                            }
                        } else {
                            System.out.print("No items added");
                            break;
                        }
                    }
                    input.close();
                    break;
                case 2:
                    System.out.print(cart.toString() + "\n"
                            + "Running total: " + cart.totalPrice);
                    break;
                case 3:
                    cart.EmptyCart();
                    break;
                case 4:
                    //output to screen and file anf finalize the list with the trim function
                    System.out.print(cart.toString() + "\n"
                            + "Please Pay: " + cart.totalPrice);
                    cart.cartTrim();
                    break;
                case 5:
                    input.close();
                    System.out.println("Thank you! Come again!");
                    System.exit(0);
            }
        }
    }

    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

0
 
LVL 47

Expert Comment

by:for_yan
ID: 34911513
Look, one obvious prblem comes to light immediately -
just let's think - your ArraList is indeed say one list in your shop
- makes sense to make it instace variable initiliize it in constructor
and populate in methods.

Now look at the item - are yousuupoposed to have one great item in your shop - no!
Item should not be instance variable.
On the contrary within the method you create items as you read lines from your
file - one Item per one line  - they whould be variable just within this method, then you
store your item in the ArrayList and then creat new Item - so you should
not have item as instance variable, you should
not create item in constructor - no surprizse that in this way you will not
have many igtems in your list but just one where you all the time
for unknown reasion change content.

Modify it before I will run your code.

And again - don't put all this lot of code in main - don't - only one line should be
in main - just
 new GoShopping()
That's it.


 
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34911608



Your accumulating products loop should be smth like that:  
ArrayList  listArray = new AraryList(); -that was even beyond method boundaries - as instance


now this is inside the method:

 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);
   item = new Item(code, name, price); <---- check order of varaibles  in  constructor
       
            item.setItemCode(code);
            item.setItemPrice(price);  <--- these you don't need if all of them can be assigned in constructor
            item.setItemName(name);


                      listArray.add(item);
           


        }

in this way for each line you create new item (that's when you say item = new Item(... - it allocates memory
all the time for new items)
and then you accumulate all items into your list -

so you have many items, but all of them are sitting in just one list
each of your items is not instace variable, but your list is - so
as long as the list will be accessible in different part of your code
you'll be able to retirieve your items frominside the list





0
 
LVL 47

Expert Comment

by:for_yan
ID: 34911821

ArrayList  listArray = new AraryList(); -that was even beyond method boundaries - as instance variable -
but withiin constrructor(just clarification to the above that it should be within constructor)

0
 

Author Comment

by:g_currier
ID: 34911872
This works.
/* Files:
 * Item.java
 * ShoppingCart.java
 * itemList.txt (Input)
 * CartSummary.txt (Output)
 */
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);
//            item.setItemCode(code);
//            item.setItemPrice(price);
//            item.setItemName(name);
//            item.setItemQuant(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 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();

            switch (choice) {
                case 1:
                    go.shopList();
                    input = new Scanner(inputFile).useDelimiter("\\-");
                    while (input.hasNextLine() && !isFull) {

                        String line = input.nextLine();
                        //String word = input.next();
                        String[] lineItem = line.split("\\-");
                        //formatted the input file, don't need trim function
                        String itemCode = lineItem[0];
                        String strPrice = lineItem[1];
                        String itemName = lineItem[2];

                        System.out.print("Add item code " + lineItem[0] + ",\"" + lineItem[2] + "\"to your cart?\n"
                                + "Type \"Y\" for Yes or \"N\" for No.\n");

                        answer = scanner.next();
                        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("Too many items in your cart. Go to checkout or empty 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

0
 
LVL 47

Expert Comment

by:for_yan
ID: 34911966
Congratulations!

it still would be a good idea to leave only one or two operators in main,
and all the rest to the constructor or methods. But of course don't break - check after each and any
change.


0
 

Author Comment

by:g_currier
ID: 34912160
I tried that and it broke...I put everything into a menuPicker() method and was then unable to go through a second round of adding stuff to the cart.  I removed the input.close() at the end of case 1 (the exception indicated that the scanner had closed - don't know why, I didn't change anything).  When cycling through the list again, I noticed that the reading of the list didn't cycle from the start each time I decided to (case 1) add items to cart.  So I left it alone and stuck with what worked.  For now, I am happy with that and can work out design and style later.  Shall we continue?  I am ready to attempt item selection by code and then applying the discount.  I will begin a new thread.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34912240
OK, leave it for now.
In general in your current design there is no reason to
do any reading of the list more than once - you should
have a constructor where you'd populate
your list from the file - after that during interaction with the
user - which should be in a separate method - there should
not be any reading from the file - you should
operate and respond to user only going through your list
So you should not need any streams or scanners at that time
as all your stuff is already neatly packaged in the items
and items are in the list. That's how it should be in general.

we should have started doing it from the very beginning then it
would have been much more organzied


0
 

Author Comment

by:g_currier
ID: 34912277
is there any reason why I could not use the list created by the shopList() method?
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now