I am having trouble with my Java assignment. I have not been having problems until now. Here is my assignment:
Modify the Inventory Program so the application can handle multiple items. Use an array to store the items. The output should display the information one product at a time, including the item number, the name of the product, the number of units in stock, the price of each unit, and the value of the inventory of that product. In addition, the output should display the value of the entire inventory. ï�· Create a method to calculate the value of the entire inventory. ï�· Create another method to sort the array items by the name of the product. And here is my current code:
Here is the error:
If I remove void I then get an error that I am leaving out the return info.
One way to approach this is to dissect the line in question and see if it's possible to figure out what the message means.
The line in question is this:The error message is this:What in that line is of "void" type? When we use the "+" operator to perform string concatenation what types of things can we concatenate with a string? What does your Inventory class actually do--create a string or just print one out?
Joined: May 03, 2009
The second piece of code is supposed to create it and the first code is supposed to display it. They are 2 different files that are supposed to me linked together...
"Current inventory is: " + myInventory.inventory()
To concatenate both the values should be string [or have toString i.e. convertible to string] . myInventory.inventory() is of return type void => which is the Root cause of error, you cannot add "void" to anything. Moreover, its a compile time error.
I dont know what did you want to achieve by appending a method returning nothing, it is anyways useless. If you just want to execute the method, do it in the next line. The question is "Why appending to a string?"
Also if you remove void, you will obviously need to specify some return type to the method and then return something of that type from the method.
I think what you are doing is mistaking a method for a constructor or vice versa. You have a method called public void inventory, which does three things. That is not a good idea; a method should do one thing.
It does these three things
Set up the contents of the inventory.
Calculate the total value of each line.
Print the details.
You ought to have the setting-up done in a constructor, but not the other two things. A constructor can be identified by
Having a name exactly the same as the name of the class (including CaSe Of LeTtErS).
Having no return type.
You should work out the inventory values when you request them. It would appear that you need a getInventoryValues method which works out all the inventory values and returns them as a double. Yes, you return a reference to an array.
Then you should organise a print() method, preferably in conjunction with a toString() method. Like thisAnd good luck and welcome to JavaRanch