Welcome to Dream.In.Code
Become a Java Expert!

Join 149,504 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,323 people online right now. Registration is fast and FREE... Join Now!




Java program - Inventory 3

 
Reply to this topicStart new topic

Java program - Inventory 3, run-time error

bigbluesky
16 Aug, 2007 - 06:36 AM
Post #1

D.I.C Head
**

Joined: 6 Jul, 2007
Posts: 54


My Contributions
this program compiles and runs - but only prints line 47 of the "book" file.
I am unsure what to do, I think something is missing like a curly bracket or a piece of code . . .

if anyone has time to take a peek . . . please help me a bit

Thank you.

-bigbluesky


Error message:

at Book.stockValueInDollars(Book.java:47)


this prints about 340 times in the command prompt window - quite shocking! LOL blink.gif



c:\Documents and Settings\Pam\My Documents\Java\Inventory\Inventory3\Inventory 3
\Inventory 3>

CODE
//Product.java

public class Product implements Comparable
{
    //Private Variables

    private String name;               //Product name
    private int identificationNumber;  //The product identification number
    private int unitsInStock;          //Number of units in stock
    private double unitPriceInDollars; //The price of each unit in dollars


    //Constructors

    //Default constructor
    public Product()
    {
        //Set some default values for each private variable
        name                  = "";
        identificationNumber  = 0;
        unitsInStock          = 0;
        unitPriceInDollars    = 0.0;

    }//End Inventory constructor

    //Initialization constructor
    public Product( String nameIn, int identificationNumberIn,
                    int unitsInStockIn, double unitPriceInDollarsIn )
    {

        //Set the item name--use the set methods to enforce bounds checking
        setName( nameIn );

        //Set the item identification number
        setIdentificationNumber( identificationNumberIn );

        //Set the number of units in stock
        setUnitsInStock( unitsInStockIn );

        //Set the unit price in dollars
        setUnitPriceInDollars( unitPriceInDollarsIn );

    }//End Inventory constructor

    //Public Methods

    //Set Methods

    //Stores the item name
    public void setName( String nameIn )
    {
        name = nameIn; //Store the item name

    }//End setName

    //Stores the product identification number
    public void setIdentificationNumber( int identificationNumberIn )
    {
        //Store the item identification number
        // If the value is negative, then store 0
        identificationNumber = ( (identificationNumberIn > 0) ? identificationNumberIn : 0 );

    }//End setID

    //Stores the number of units in stock
    public void setUnitsInStock( int unitsInStockIn )
    {
        //Store the number of units in stock
        // If the value is negative, then store 0
        unitsInStock = ( (unitsInStockIn > 0)?unitsInStockIn:0 );

    }//End setUnitsInStock

    //Stores the price of each unit in dollars
    public void setUnitPriceInDollars( double unitPriceInDollarsIn )
    {
        //Store the unit price
        // If the value is negative, then store 0.0
        unitPriceInDollars = ( (unitPriceInDollarsIn > 0.0)?unitPriceInDollarsIn:0.0);

    }//End setUnitPriceInDollars

    //Get Methods

    //Returns the item name
    public String getName()
    {
        return ( name ); //Return the identification name

    } // End getName

    //Returns the item identification number
    public int getIdentificationNumber()
    {
        return ( identificationNumber ); //Return the identification number

    }//End getIdentificationNumber

    //Returns the number of units in stock
    public int getUnitsInStock()
    {
        return( unitsInStock ); //Return the number of units in stock

    }//End getUnitsInStock

    //Returns the price of each unit
    public double getUnitPriceInDollars()
    {
        return( unitPriceInDollars ); //Return the unit price

    }//End getUnitPriceInDollars

    //Other Methods

    //Returns the total value of the inventory in dollars
    public double stockValueInDollars()
    {
        return ( unitsInStock * unitPriceInDollars );

    }//End stockValueInDollars

    public static double totalInventoryValue( Product inventory[] )
    {
      double value = 0.0;
      for(Product p: inventory)
      {
       value += p.stockValueInDollars();
      }//End for
      return( value );
    }//End method totalInventoryValue

    //Overloads the String objects compareTo() method so Products can be
    //compared and potentially sorted by name.
    public int compareTo (Object o)
    {
        String s2 = ((Product)o).name.toUpperCase();
        String s1 = name.toUpperCase();
        return ( s1.compareTo(s2) );

     } //End compareTo

    //Returns a formatted String for output purposes
    public String toString()
    {
        String formatString = "Identification Number : %d\n";
        formatString       += "Product               : %s\n";
        formatString       += "Units In Stock        : %d\n";
        formatString       += "Unit Price            : $%.2f\n";
        formatString       += "Stock Value           : $%.2f\n\n";

        return ( String.format( formatString, identificationNumber, name, unitsInStock,
                                unitPriceInDollars, stockValueInDollars())
               );

    }//End toString()

}//End class Product





CODE
import java.util.Arrays; //For Arrays.sort

public class Inventory3
{
    public static void main( String args[] )
    {
      double totalInventoryValue = 0.0;

      Book [] inventory;
      inventory = new Book[3];

      inventory[0] = new Book("Inkspell", "Funke, Cornellia", 1, 600, 20.00);
      inventory[1] = new Book("Thousand Orcs, The", "Salvatore, RA", 2, 800, 25.95);
      inventory[2] = new Book("Harry Potter and the Half Blood Prince", "Rowling, JK", 3, 1000, 29.99);

       //Sort the array
      Arrays.sort( inventory );

      //print out each Book
      for (Book book:inventory)
      {
          //Print this Book
          System.out.println( book.toString() );

      }//End for

      //Print out totalInventoryValue in dollars
      totalInventoryValue = Product.totalInventoryValue( inventory );

      System.out.printf( "Total Inventory Value : $%.2f\n", totalInventoryValue );

     } //End method main

}//End Inventory3





CODE
//In a file Book.java

public class Book extends Product implements Comparable
{
    //Variables
    private String author; //Book author

    //Constructors

    //Initailization constructor
    public Book(String titleIn, String authorIn, int idIn, int unitsInStockIn, double unitPriceInDollarsIn)
    {
        //Call super class contructor
        super( titleIn, idIn, unitsInStockIn, unitPriceInDollarsIn);

        //Call a set method to ensure proper initialization
        setAuthor( authorIn );

    }//End Book constructor

    //Public Methods
    //Set Methods

        //Store Book author
        public void setAuthor( String authorIn )
        {
            author = authorIn;

        } // end method setAuthor

    //Get Methods

         //Return Book Author
         public String getAuthor()
         {
             return ( author ); //Return Book author

         }//End getAuthor

    //Other Methods

         //Calculate the stock value
        // Returns total value of product in stock, adding a %5 restocking fee
        public double stockValueInDollars()
        {
          // Add a 5% restocking fee
          return(stockValueInDollars() * 1.05);

        } // End stockValueInDollars

        //A method for returning the restockingFee()
        public double restockingFee()
        {
            //Return 5% of the super-class stock value
            return( super.stockValueInDollars() * 0.05 );

         }//End method for returning restockingFee

        //Display

        //Returns a formatted String for output purposes
        public String toString()
        {
                String formatString         = "Book Title            : %s\n";
                formatString               += "Restocking Fee        : $%.2f\n";

                //Create a formatted string
                formatString = String.format(formatString, author, restockingFee() );

                //Return the string for use in display
                return( formatString + super.toString() );

         }//End toString()

    }//End class Book




User is offlineProfile CardPM
+Quote Post

William_Wilson
RE: Java Program - Inventory 3
16 Aug, 2007 - 06:44 AM
Post #2

lost in compilation
Group Icon

Joined: 23 Dec, 2005
Posts: 4,101



Thanked: 25 times
Dream Kudos: 3275
Expert In: Java, C, Javascript

My Contributions
what is the error? such as:
null pointer
array out of bounds
illegal indirection
buffer overflow
...etc...

this will make it much easier to figure out the problem

your error does however have to do with the fact that you recursively call stockValueInDollars() from inside this method... thus it continually calls itself and nothing is returned, which after enough loops returns an error.
User is offlineProfile CardPM
+Quote Post

bigbluesky
RE: Java Program - Inventory 3
16 Aug, 2007 - 09:53 AM
Post #3

D.I.C Head
**

Joined: 6 Jul, 2007
Posts: 54


My Contributions
QUOTE(William_Wilson @ 16 Aug, 2007 - 07:44 AM) *

what is the error? such as:
null pointer
array out of bounds
illegal indirection
buffer overflow
...etc...

this will make it much easier to figure out the problem

your error does however have to do with the fact that you recursively call stockValueInDollars() from inside this method... thus it continually calls itself and nothing is returned, which after enough loops returns an error.




ok - that must be what the problem is - no error is stated - it compiles then just prints that same line over and over.

I am not sure how to correct this . . .

thank you.

-bigbluesky
User is offlineProfile CardPM
+Quote Post

Martyr2
RE: Java Program - Inventory 3
16 Aug, 2007 - 11:08 AM
Post #4

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,655



Thanked: 313 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
Rule 1 when creating any recursive function (a function that calls itself), make sure it has what is known as a "bottom" or a condition which is tested to let the function know that it can't go any further or has found the simplest case. For instance, lets say we were going to make a recursive function to show a hierarchy tree of folders, like windows explorer. We would start by calling a function which would call itself for each subfolder it has. How does it know when it has hit a bottom? When you test for the existence of more folders and it returns none. Then it knows to return from the call and go back up the tree and down into another sub folder.

The problem you have is that there is no way for the function to know when it has hit the bottom because there is no test.

However there is a bigger issue here. Why are you calling itself in the function to begin with? You have defined that function in the "book" class so simply it should return the book's value with the 5% on it. Straight forward function. The inventory class then will loop through it's books and ask each book for its value plus the 5% the book has already calculated for itself.

So in theory that function should look like...

CODE

//Calculate the stock value
// Returns total value of product in stock, adding a %5 restocking fee

public double stockValueInDollars()
{
         // Add a 5% restocking fee
         return((unitsInStock * unitPriceInDollars) * 1.05);

} // End stockValueInDollars


This function returns the books price with the 5% restocking fee.

Then in your inventory class when you go to get the value of your items, you can loop through your products and ask each product for its value and it will give you the value based on the base class Product or if it is a book it will use this overridden method to give you the price of the book plus the 5% restocking fee.

Hopefully that makes sense. I am just saying I don't think you need recursion here. smile.gif
User is offlineProfile CardPM
+Quote Post

bigbluesky
RE: Java Program - Inventory 3
16 Aug, 2007 - 05:31 PM
Post #5

D.I.C Head
**

Joined: 6 Jul, 2007
Posts: 54


My Contributions
QUOTE(Martyr2 @ 16 Aug, 2007 - 12:08 PM) *

Rule 1 when creating any recursive function (a function that calls itself), make sure it has what is known as a "bottom" or a condition which is tested to let the function know that it can't go any further or has found the simplest case. For instance, lets say we were going to make a recursive function to show a hierarchy tree of folders, like windows explorer. We would start by calling a function which would call itself for each subfolder it has. How does it know when it has hit a bottom? When you test for the existence of more folders and it returns none. Then it knows to return from the call and go back up the tree and down into another sub folder.

The problem you have is that there is no way for the function to know when it has hit the bottom because there is no test.

However there is a bigger issue here. Why are you calling itself in the function to begin with? You have defined that function in the "book" class so simply it should return the book's value with the 5% on it. Straight forward function. The inventory class then will loop through it's books and ask each book for its value plus the 5% the book has already calculated for itself.

So in theory that function should look like...

CODE

//Calculate the stock value
// Returns total value of product in stock, adding a %5 restocking fee

public double stockValueInDollars()
{
         // Add a 5% restocking fee
         return((unitsInStock * unitPriceInDollars) * 1.05);

} // End stockValueInDollars


This function returns the books price with the 5% restocking fee.

Then in your inventory class when you go to get the value of your items, you can loop through your products and ask each product for its value and it will give you the value based on the base class Product or if it is a book it will use this overridden method to give you the price of the book plus the 5% restocking fee.

Hopefully that makes sense. I am just saying I don't think you need recursion here. smile.gif



Thank you so much for your time! I got it!
It worked! between the two of you, I was able to find my mistake!

I changed my code from:

CODE
//Calculate the stock value
        // Returns total value of product in stock, adding a %5 restocking fee
        public double stockValueInDollars()
        {
          // Add a 5% restocking fee
          return(stockValueInDollars() * 1.05);

        } // End stockValueInDollars


to this: (I added the word "super")

CODE
//Calculate the stock value
        // Returns total value of product in stock, adding a %5 restocking fee
        public double stockValueInDollars()
        {
          // Add a 5% restocking fee
          return(super.stockValueInDollars() * 1.05);

        } // End stockValueInDollars


I am beginning to think that there is more than one way to get code to work in Java - just as there is more than one way to skin a cat - so I am sure some other solution would have worked as well.

Thanks again! biggrin.gif

-bigbluesky
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/7/09 06:53PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month