Well, I was going to call it a day and just relax for the rest of the weekend, but Peter got me all fired up, so before I shut her down I decided to throw one more twist. Wouldn't it be clever to keep a running total of the values? I thought. I currently display the value of each cd depending on how many are in stock and its price.
How hard could it be to just sum that field. Apparently harder than I though. Here is what I came up with: Value being the name of the parameter already used, and cdCount being my counter.

public static float calculateTotal(Inventory completeValue[]);
			
				float totalValue = 0;
				for ( int cdCount = 0; cdCount < completeValue.length; cdCount++ )
				{
				totalValue += completeValue[cdCount].getValue();
				} // end for
				return totalValue;

I just inserted that at the bottom of my Compactdisk class, right after the brace that closes return(price * nstock);, but before the one that ends the class.
I get
Compactdisk.java:79: illegal start of type
for ( int cdCount = 0; cdCount < completeValue.length; cdCount++ )
^
Compactdisk.java:83: <identifier> expected
return totalValue;

I thought this would be simple, can anyone see what I am missing? It almost looks to me as if it does not like the method there at all.

public static float calculateTotal(Inventory completeValue[]);			
	float totalValue = 0;
	for ( int cdCount = 0; cdCount < completeValue.length; cdCount++ )
	{
		totalValue += completeValue[cdCount].getValue();
	} // end for
	return totalValue;
public static float calculateTotal(Inventory completeValue[])
{			
	float totalValue = 0;
	for ( int cdCount = 0; cdCount < completeValue.length; cdCount++ )
	{
		totalValue += completeValue[cdCount].getValue();
	} // end for
	return totalValue;
}

That could be the case for start...

You array program works great. I do have one suggestion though. At the moment you have an array of 5 elements but the loop continues until the user types stop. What would happen if there were six iterations? I would suggest using a for loop limiting the loops to five iterations. You could then implement an if(userinput == "stop") statement with a break statement to exit the loop prematurely.

I agree. I was going to make that one of my housecleaning chores today. I wanted to get the value summed up, print a list of the entire inventory, and then raise the array limit to 100 or so and put the check in that you just recommended.
Right now I am stuck on the Value sum, and since this thread was concerning the array I am going to close it out.
If the summing issue contiues to kick my butt I will open a different thread on it later.

Thanks for all your help guys.

Member Avatar for iamthwee

Another point worth considering, is that you can interface your existing classes with the ArrayList.

That should afford greater flexibility in regards to adding, removing and storing custom objects.

hey man, how can u assign a String object to an array directly.. make the following changein the set method

public void setCDName(String diskName)
       {
       cdName[0] = diskName;
// stores diskName in 0 th location
// u can take a counter variable to point to the index so that u can increment each time u r adding a new element
       }

and in getCDName() method u hav given the return type as String but u r trying to return an array... this results in an error as both types are incompatible

so make the following change

public String[] getCDName()
        {   
        return cdName;
        }

this will return the entire array cdName to the caller

commented: Not using code tags to insert code into post and providing the lamest solution ever seen -1

Got it ... I think.
I put the Compactdisk class back in, and just modified it for the new array ... at least that is what I think I did.
It looks good, it runs well ( a few bugs to work out, but I think I have it)
Tell me what you think Ezzaral, I might have to put your name as a reference in this somewhere if I ever get it working! :o)
Just look at the name variable right now, that is all I have implimented at this point. Here is the main class.

Ok, I'll inline and comment a few things in your code below. It's very close, but inadvertently you have altered your loop to keep working on the same object over and over for several of the property sets. If you wish to use a simple variable to reference them, instead of cds[#], you will need to set the variable to point to the array entry you want to work with. If you are still confused by the cds[0].getName() style code, just remember that cds[] array contains all of your cd objects and by using cds[#] you can operate on the one you want exactly like you would any other variable that pointed to a cd (ie thisCompactdisk). Take a look at the parts I have changed in your code below.

import java.util.Scanner; //uses class Scanner

public class Inventory
{// begin class Inventory
    public static void main(String[] args)    
    {//begin method main
    
    Compactdisk thisCompactdisk = null;  // set up one variable of type Compactdisk to work with - no value yet because the user hasn't entered anything;

    // create cd Array
    Compactdisk[] cds = new Compactdisk[5];

    // commenting these out - user hasn't entered a CD yet
    // so you don't need to create one yet..
    //cds[0] = new Compactdisk(); // adds to array
    //cds[0].getName();
    
    int cdCount=0;
    
    Scanner input = new Scanner(System.in);  // create scanner
    
    String nameInput = input.next();
    
            // begin display method
            System.out.print("Enter CD Name or STOP to Exit: ");
            nameInput = input.next();  // read cd name
            
            
              while (!nameInput.equalsIgnoreCase("STOP"))
            {// begin main While
            
                // create a new cd - we don't really need to add to array yet here
                thisCompactdisk = new Compactdisk();
                // set the cd properties
                thisCompactdisk.setName(nameInput);

                System.out.print("Enter Price of this CD: "); // prompt for price
                thisCompactdisk.setPrice(input.nextFloat());    // price input from user.
                while (thisCompactdisk.getPrice()<= 0)
                {// begin while
                System.out.print("Price Must Be Greater Than Zero. Enter Price: ");
                thisCompactdisk.setPrice(input.nextFloat()); // cd price loop from user.
                } // End while
        
                System.out.print("Enter CD Item Number: "); // prompt for cd item number
                thisCompactdisk.setItemno(input.nextInt()); // cds item number input from user
        
                System.out.print("Enter Number of these CDs in Stock: "); // prompt for cd stock
                thisCompactdisk.setNstock(input.nextInt()); // cds in stock input from user
                
        
                System.out.print("CD "+thisCompactdisk.getName()+", Item Number "+thisCompactdisk.getItemno()+","); // display name
                System.out.printf(" is worth %c%.2f.\n", '$', thisCompactdisk.getPrice()); // display individual price
                System.out.printf("We have %d copies in stock, making our inventory worth %c%.2f\n", thisCompactdisk.getNstock(), '$', thisCompactdisk.getValue()); //inventory value
        
                // ok, done setting the cd data so add this one
                // to the array
                cds[cdCount] = thisCompactdisk;

                cdCount++;
                System.out.print("Enter CD Name or STOP to Exit: "); // internal loop prompt
                nameInput = input.next(); //name input from user
                        
            } // End main While
        System.out.print("Ending Program.");
    

    }// end method main
} // end class Payroll

You will see that you don't need to create the cd until the user has entered one. The variables "thisCompactdisk" and "cds[0]" (just using the first element 0 here for example) both point to a cd object and can be used interchangeably. On the second loop iteration, "thisCompactdisk" is set to point to a new Compactdisk object. cds[0] still contains your first cd. At this point cds[0] and thisCompactdisk are no longer referring to the cd anymore. thisCompactdisk is just acting as a pointer to the cd object you are currently working with, while the cds are still in the cds[] array. I hope that clear up the confusion a bit. Keep in mind, you don't really need the "thisCompactdisk" variable at all, you could work with all the cds with the "cd[cdCount].setXXX()" style code and it would all be fine. The variable "thisCompactdisk" is only there for convenience if you don't like typing "cds[cdCount" each time.

Well, I was going to call it a day and just relax for the rest of the weekend, but Peter got me all fired up, so before I shut her down I decided to throw one more twist. Wouldn't it be clever to keep a running total of the values? I thought. I currently display the value of each cd depending on how many are in stock and its price.
How hard could it be to just sum that field. Apparently harder than I though. Here is what I came up with: Value being the name of the parameter already used, and cdCount being my counter.

public static float calculateTotal(Inventory completeValue[]);
            
                float totalValue = 0;
                for ( int cdCount = 0; cdCount < completeValue.length; cdCount++ )
                {
                totalValue += completeValue[cdCount].getValue();
                } // end for
                return totalValue;

I just inserted that at the bottom of my Compactdisk class, right after the brace that closes return(price * nstock);, but before the one that ends the class.
I get
Compactdisk.java:79: illegal start of type
for ( int cdCount = 0; cdCount < completeValue.length; cdCount++ )
^
Compactdisk.java:83: <identifier> expected
return totalValue;

I thought this would be simple, can anyone see what I am missing? It almost looks to me as if it does not like the method there at all.

See peter_budo's post on your method. You just didn't put your braces in correctly and you have a semi-colon at the end of the line you declare the method. Beside that your method is correct!

You actually do not need to define this in the Compactdisk class. You can put it in the Inventory class instead, but be sure that you don't try to put it inside the main() method. The compiler won't like that. The method makes more sense on the Inventory class, since that one is responsible for keeping track of many cds and reporting things about that collection. The Compactdisk class represents a single cd. It has no knowledge of other cds or of your collection of them in Inventory. It doesn't need to know about those other ones, just itself. Keep that in mind with your print method too. Add behavior (methods) and data (properties) to the classes which make the most sense in your view of how the different pieces should interact. Treat them as separate entities with separate responsibilities and information.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.