Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 19 of 19

Thread: URGENT! Why won't my addToInvoice method work?

  1. #1
    Member
    Join Date
    Mar 2013
    Posts
    58
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default URGENT! Why won't my addToInvoice method work?

    Hey guys,
    I'm working on arrays and I'm just not getting the hang of it. Every time my addToInvoice method is called and printed, it's not coming out correctly. Here's what the output is supposed to look like when you choose option 1 or 3.
    This line serves customers with 5 or fewer items
    ------------------------------------------------

    1. Buy an item
    2. Modify the quantity of an item
    3. Show the items purchased so far
    4. Done

    Your choice:
    1
    Enter the product name: Walnuts
    Enter the price: 9.99
    How many of Walnuts did you buy? Please enter the quantity: 2

    1. Buy an item
    2. Modify the quantity of an item
    3. Show the items purchased so far
    4. Done

    Your choice:
    3
    Product: Walnuts Price: $9.99 Quantity: 2
    Product: 1% Milk Price: $1.99 Quantity: 2
    Running Total: $23.96


    And here is what my output is giving me:
    1
    Enter the product name: milk
    Enter the price: 2.99
    How many of milk did you buy? Please enter the quantity: 2
    1. Buy an item
    2. Modify the quantity of an item
    3. Show the items purchased so far
    4. Done

    Your choice:
    1
    Enter the product name: soup
    Enter the price: 1.99
    How many of soup did you buy? Please enter the quantity: 1
    1. Buy an item
    2. Modify the quantity of an item
    3. Show the items purchased so far
    4. Done

    Your choice:
    1
    Enter the product name: sauce
    Enter the price: 2.39
    How many of sauce did you buy? Please enter the quantity: 1
    1. Buy an item
    2. Modify the quantity of an item
    3. Show the items purchased so far
    4. Done

    Your choice:
    3
    null

    null

    Produt: Product: sauce Price: $2.39 Price: 0.0 Quantity: 1

    null

    null


    Here is my product class:
    public class Product   {
        private String name;
        private double price;
     
     
        public Product(String name, double price) {
            this.name = name;
            this.price = price;
        }
     
     
        public void setName(String name)   {
            this.name = name;
        }
     
     
        public String getName()  {
            return name;
        }
     
     
        public void setPrice(double price)  {
            this.price = price;
        }
     
     
        public double getPrice()  {
            return price;
        }
     
     
        public String toString()  {
            NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
            return "Product: " + name + "\tPrice: " + n.format(price);
        }
    }

    And my LineItem class:

    public class LineItem
    {
        private Product p;
        private int quantity;
        private double amountOwed;
        private int q;
        private double price;
        public LineItem(Product p, int quantity) {
            this.p=p;
            this.quantity=quantity;
        }
     
        public double getAmount() {
            return quantity*price;
        }
     
        public void setQuantity(int q) {
            this.q=q;
        }
     
        public int getQuantity() {
            return quantity;
        }
     
        public Product getProduct() {
            return p;
        }
     
        public java.lang.String toString() {
            return "Produt: " + p + "\tPrice: " + price + "\tQuantity: " + quantity + " ";
        }
    }

    And my invoice method:
    public class Invoice
    {
        private LineItem[] collection;
        private int numItems;
        private double runningTotal=0;
        private double price;
        private int quantity;
     
        public Invoice() {
            numItems=0;
        }
     
        public void addToInvoice(LineItem item) {
            collection=new LineItem[5];
            collection[numItems]=item;
            numItems++;
        }
     
        public int getNumItems() {
            return numItems;
        }
     
        public double getRunningTotal() {
            return runningTotal;
        }
     
        public void print() {
            for (int i=0; i<5; i++) {
            System.out.println(collection[i] + "\n");
            runningTotal = runningTotal + price*quantity;
           }
           getRunningTotal();
        }
     
        public void update(java.lang.String name, int quantity) {
     
        }
    }

    AND FINALLY my main method:
    public class Cashier   {
        public static void main(String args[]) { 
            final int MAXITEMS = 5;
            Scanner keyboard = new Scanner(System.in);
            NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); 
            System.out.println("Welcome to CS 140 Store Express Line");
            System.out.println("This line serves customers with " + MAXITEMS + " or fewer items");
            System.out.println("------------------------------------------------\n");
     
            Invoice invoice = new Invoice();
            do {
                System.out.println("\t1. Buy an item");
                System.out.println("\t2. Modify the quantity of an item");
                System.out.println("\t3. Show the items purchased so far");
                System.out.println("\t4. Done");
                System.out.println("\nYour choice: ");
                int choice = Integer.parseInt(keyboard.nextLine());
                switch(choice) {
                    case 1:
                       if (invoice.getNumItems() < MAXITEMS) {
                           System.out.print("Enter the product name: ");
                           String name = keyboard.nextLine();
     
                           System.out.print("Enter the price: ");
                           double price = Double.parseDouble(keyboard.nextLine() );
     
                           System.out.print("How many of " + name + " did you buy? Please enter the quantity: ");
                           int quantity = Integer.parseInt(keyboard.nextLine() );
                           LineItem item = new LineItem(new Product(name, price), quantity);
                           invoice.addToInvoice(item);
                       }
                       else
                           System.out.println("This line is customers for <= " + MAXITEMS + " items only");
                       break;
     
                    case 2:
                       System.out.println("Enter the name of the product");
                       String name = keyboard.nextLine();
                       System.out.println("Enter the new quantity: ");
                       int quantity = Integer.parseInt(keyboard.nextLine() );
                       invoice.update(name, quantity);
                       break;
     
                    case 3:
                       invoice.print();
                       break;
     
                    case 4:
                       System.out.println("Thanks for using CS 140 store");
                       System.out.println("Here is your invoice information");
                       System.out.println("--------------------------------");
                       invoice.print();
                       System.out.println("\nPlease come back again.  Have a nice day!");
                       System.exit(0);
     
                    default:
                       System.out.println("Wrong choice.  Choose a valid option");
                }    // end of switch 
            }  while (true);  // end of do - while loop
        }     // end of main method
    }   // end of Cashier class

    can anyone tell me what I'm doing wrong?


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    Where are the Strings coming from that have the null values? Start at the the println() statement that printed the null and back track in the code to see where the null value is coming from.


    The posted code will not compile for testing because of missing import statements.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Mar 2013
    Posts
    58
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    The println() statement is printing the collection at all 5 positions. The last 3 positions have nothing in them so I think that's why I'm getting null. I don't know if I declared the array correctly within the addToInvoice method because the output should only print positions in the collection that have something in them. But I don't know why the first position is printing null, and why Product: prints twice and Price: prints twice.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    The last 3 positions have nothing in them so I think that's why I'm getting null
    Yes, empty slots in an array would have null values. The code should keep track of how many slots in the array are used or test if they have null values before trying to use them.


    The posted code will not compile for testing because of missing import statements.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Mar 2013
    Posts
    58
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    Okay so for the last 3 spots giving null, I changed my method's for loop to only print as many items as I have put in by switching my code to
        public void print() {
            for (int i=0; i<numItems; i++) {
            System.out.println(collection[i] + "\n");
            runningTotal = runningTotal + price*quantity;
           }
           System.out.println(getRunningTotal());
        }

    So now I'm just getting after adding only two products (milk & butter):
    1. Buy an item
    2. Modify the quantity of an item
    3. Show the items purchased so far
    4. Done

    Your choice:
    3
    null

    Produt: Product: Butter Price: $1.29 Price: 0.0 Quantity: 1

    0.0


    But I don't know why I'm getting null for the first position and why product and price are printing twice.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    I don't know why I'm getting null fo
    What variable has the null value that is being printed? Then backtrack in the code to find out why that variable does not have a valid value.

    Produt: Product: Butter Price: $1.29 Price: 0.0 Quantity: 1

    Does the text in red look familiar? Where does that text come from?
    What value does the variable: p have in it? What String will be returned when that variable is concatenated in a String.
    Hint: the toString() method for p's class will be called.


    The posted code will not compile for testing because of missing import statements.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Mar 2013
    Posts
    58
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    The first position in the collection is giving me the null value.

    I'm sorry, I don't quite understand everything in Java programming enough to figure out without a general example, and just telling me I'm missing an import statement does not really help me. This is my first class for programming and unfortunately I had no choice but to take it online. I don't learn well that way. But I had to take the class or I will lose my commission as an officer in the Navy. That being said, the textbook that was given for the class has about 4 pages for chapter and is pretty much useless so I'm stuck trying to figure this out on my own. I really appreciate your help so far but will all due respect sir, I am swallowing my pride and asking you if you could dumb it down for me. I'm trying my best to finish this by tomorrow night.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    How do you compile the code you have posted? The compiler needs to know what package a class is in so it can find its definition. The import statement names the package a class is in so the compiler can find it.

    The posted code MUST have import statements so it will compile. Did you skip copying them when you copied the code you posted? The import statements are at the beginning of the source file.

    Here are some examples:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.GeneralPath;

    The first position in the collection is giving me the null value.
    How or why is the program skipping putting a value into the first position.
    Remember index values for arrays start at 0.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Member
    Join Date
    Mar 2013
    Posts
    58
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    The only import statements I was given to use are
    import java.text.*;     // for NumberFormat
    import java.util.*;     // for Locale
    in the product class and
    import java.util.Scanner;
    import java.text.*;      // for the NumberFormat 
    import java.util.*;
    in the main method Cashier. Sorry I didn't realize I didn't paste them/[COLOR="Silver"]

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    Can you give me the responses I need to make to test the code? Just what I type in.
    I tried this:
    1
    soup
    2.39
    1
    3

    My IDE does not support an active console so I put the responses in a String that the Scanner class will read from:
            System.setIn(new java.io.ByteArrayInputStream("1\nsoup\n2.39\n1\n3\n4\n".getBytes())); 
    //<<Scanner input

    I get this output:
    Running: java -cp . Cashier

    Welcome to CS 140 Store Express Line
    This line serves customers with 5 or fewer items
    ------------------------------------------------

    1. Buy an item
    2. Modify the quantity of an item
    3. Show the items purchased so far
    4. Done

    Your choice:
    Enter the product name: Enter the price: How many of soup did you buy? Please enter the quantity: 1. Buy an item
    2. Modify the quantity of an item
    3. Show the items purchased so far
    4. Done

    Your choice:
    Product: soup Price: $2.39 Quantity: 1

    1. Buy an item
    2. Modify the quantity of an item
    3. Show the items purchased so far
    4. Done

    Your choice:
    Thanks for using CS 140 store
    Here is your invoice information
    --------------------------------
    Product: soup Price: $2.39 Quantity: 1

    Please come back again. Have a nice day!

    0 error(s)
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Member
    Join Date
    Mar 2013
    Posts
    58
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    --- Update ---

    [/COLOR]I think the reason it is skipping position zero has something to do with this method:
        public void addToInvoice(LineItem item) {
            collection=new LineItem[5];
            collection[numItems]=item;
            numItems++;
        }
    but I thought when I wrote collection[numItems]=item; it was telling the compiler to put the first product in position 0 since numItems was initialized to zero. So I'm not sure why it is skipping.

    --- Update ---

    The response 1 means you're telling the system you're buying another product. So it asks for the product name, price and quantity. Then prompts you again. If you want to buy another item you enter 1 again. Entering 3 gets the program to give you a list of what you have bought so far and tells you the name, price, and quantity of each as well as the running total of the entire invoice at the end.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    I updated my last post. The output for 1 product looked ok.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Member
    Join Date
    Mar 2013
    Posts
    58
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    Oh I see what you mean about not having an active console. It looks like to me yours output is right.. Could you guide me on what to do next?

    --- Update ---

    Okay I tried only doing one product too and mine worked other than posting the product and price twice like before. Why is it that when I add a second product the first becomes null?

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    Why is it that when I add a second product the first becomes null?
    That means that the first value you added has been lost. If you create a new array every time you add an item, all the items in the previous array are lost. Make sure you create the array one time at the beginning and not each time an item is added.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Member
    Join Date
    Mar 2013
    Posts
    58
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    I realized by creating the collection in addToInvoice was creating a new collection every time addToInvoice is called. So I updated these two methods to:
        public Invoice() {
            collection=new LineItem[5];
            numItems=0;
        }
     
        public void addToInvoice(LineItem item) {
            collection[numItems]=item;
            numItems++;
        }

    and I got (after adding two products milk & butter):
    1. Buy an item
    2. Modify the quantity of an item
    3. Show the items purchased so far
    4. Done

    Your choice:
    3
    Produt: Product: Milk Price: $2.99 Price: 0.0 Quantity: 1

    Produt: Product: Butter Price: $1.99 Price: 0.0 Quantity: 2

    0.0

    So we're getting there, thank you very much. I think the next thing I need to clear is the double print of product: and price: I purposely misspelled Product: from the LineItem class so I could figure out which is which. But I'm still unclear of why it's being printed twice.

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    why it's being printed twice.
    Look at post #6 again. Especially the hint.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Member
    Join Date
    Mar 2013
    Posts
    58
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    So p's toString() is being called and I'm assuming that's the one I want to print. But I think the toString is being printed from LineItem too... I was instructed to create a toString for LineItem to "Return a string representation of this line item " but I don't understand what for, because it looks like the product toString and the LineItem toString share the same attributes. Should I get rid of the LineItem toString?

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    looks like the product toString and the LineItem toString share the same attributes.
    Do some experimenting by changing what the LineItem class's toString() method returns. Some combination of variables and Strings should give you what you want.

    I'm done for tonight.
    If you don't understand my answer, don't ignore it, ask a question.

  19. #19
    Member
    Join Date
    Mar 2013
    Posts
    58
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: URGENT! Why won't my addToInvoice method work?

    Thank you very much sir, I was able to figure it out. The final thing I need to do is write the method for public void update(java.lang.String name, int quantity) but I think I can do it. I appreciate the help. Have a good night.

Similar Threads

  1. do-while loop won't work
    By ncampbell605 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 12th, 2012, 10:07 AM
  2. Image won't work!
    By mkrage in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 26th, 2012, 05:08 PM
  3. Why won't this for loop work?
    By vwillis in forum Loops & Control Statements
    Replies: 1
    Last Post: October 14th, 2011, 12:49 PM
  4. MergeSort won't work
    By joshft91 in forum What's Wrong With My Code?
    Replies: 7
    Last Post: February 7th, 2011, 09:44 PM
  5. My lines won't work!!!
    By The Mewzytion in forum What's Wrong With My Code?
    Replies: 5
    Last Post: July 2nd, 2010, 10:24 AM

Tags for this Thread