Thursday, April 19, 2012

Java: How do i create objects in a static method and also call for methods from another class?

I am doing this Java assignment for hours and stuck with this tester class for very almost 5 hours.



In this assignment, I have created a Product class, a Money class, a LineItem class and an Inventory class. Now i need to create a test class to test the program by putting new lineitems into the inventory array.



In the tester class, I am trying to create a static method public static void addTestItems(Inventory theInventory) which suppose to add 4 items. For each item I will need to create a product object followed by a LineItem object to contain the newly created product. next i need to use a method from the inventory class to add the items into the array in the inventory class.



What i have tried too so far:



private static void addTestItems(Inventory theInventory)
{
Inventory[] _items;
Product product1 = new Product("Book","Objects first with Java"," An excellent introductory Java textbook");
Product product2 = new Product("CD","The dark side of the moon","The all-time classic Pink Floyd album");
Product product3 = new Product("DVD", "Transformers","Robots in disguise");
Product product4 = new Product("Laptop","Lenovo T42","A good yet affordabble laptop");
Money unitPrice1 = new Money(29,99);
Money unitPrice2 = new Money(4,99);
Money unitPrice3 = new Money(9,99);
Money unitPrice4 = new Money(450,0);
_items[1] = new LineItem(product1,5,unitPrice1);
_items[2] = new LineItem(product2,8,unitPrice2);
_items[3] = new LineItem(product3,200,unitPrice3);
_items[4] = new LineItem(product4,9,unitPrice4);
}


The current error is incompatible types- found LineItem but expected Inventory so i tried changing Inventory[] _items; to LineItem[] _items;. But the error was variable _items may not be initialise.



Sorry guys I am a real noob in Java, I tried searching on-line for ages but I do not quite understand most results. The only one i understand was http://forums.devshed.com/java-help-9/bluej-compiler-error-cannot-find-symbol-variable-object-688573.html but i tired putting into my context but failed. I also found lot of results but they had constructors and instance variables in them which my teacher specifically mentioned that I will not need them.



Wonder if expert could guide me along like let me know my mistakes. Thanks thanks.





No comments:

Post a Comment