help troubleshooting code...
I have 3 java classes that should do the trick i am intending to do... but the magic aint happening. Please help me spot where is the mistake, as I can't find it myself no matter what...
First the Product Class:
/*
* Product.java
*
* Created on June 26, 2007, 10:47 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package inventoryprogram;
/**
*
* @author JL Morales
*
*/
publicclass Productextends Object{
private String Name;// product Name
privatedouble Price;// Price per product
privateintQty;// quantity in stock
privateintSku;// Sku number
private String Category;// Category Name
public Product(String Name,int Sku,int Qty,double Price,String Category){// argument constructor
this.Name = Name;
this.Sku= Sku;
this.Qty= Qty;
this.Price = Price;
this.Category = Category;
}// end four-argument constructor
//begin with getters
public String getName(){
return this.Name;
}
public String getCat(){
return this.Category=Category;
}
publicdouble getPrice(){
return this.Price=Price;
}
publicint getQty(){
return this.Qty;
}
//done with getter methods
// calculate item value
publicdouble getValue(){
return this.Price * this.Qty;
}// end method item value
// return String representation of item object
public String toString(){
return String.format("%s: %s\n%s: %s\n%s: %d\n%s: %d\n%s: %.2f",
"Category", Category,
"Name", Name,
"Sku", Sku,
"Qty", Qty,
"Price", Price);
}// end method toString
}// end class Product
Now the SubProduct sub class...
/*
* SubProduct.java
*
* Created on July 7, 2007, 9:59 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package inventoryprogram;
/**
*
* @author Owner
*/
publicclass SubProductextends Product{
/** Creates a new instance of SubProduct */
public SubProduct(String Name,int Sku,int Qty,double Price,String Category){
super(Name, Sku, Qty, Price, Category);//validate & store product variables into sub class variable instances
}
//calculate restocking fees
publicdouble calcRestocking(){
return (super.getPrice() * 0.05) + super.getPrice();
}
public String getRestockingFee(){
return String.format("%s: $%.2f","Restocking Fee",calcRestocking());
}
}
And last, the main class:
/*
* Main.java
*
* Created on June 26, 2007, 4:21 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package inventoryprogram;
import java.util.*;
import java.awt.*;
/**
*
* @author JL Morales
*
*/
publicclass Main{
/** Creates a new instance of Main */
public Main(){
}
private Product[] myProducts ={//create inventory array of items for use with product class
new Product("Pencils",528646,312,0.15,"Office Supplies"),
new Product("Pens",673467,233,1.00,"Office Supplies"),
new Product("Markers",245798,112,1.76,"Office Supplies"),
new Product("Highlighter",478469,324,1.95,"Office Supplies"),
new Product("Eraser",143100,127,0.10,"Office Supplies"),
new Product("Tacks",102701,309,1.00,"Office Supplies"),
new Product("Optical Mouse",379465,24,22.95,"Computing"),
new Product("Compact Keyboard",340987,18,30.00,"Computing"),
new Product("USB Port Extender",234098,21,12.99,"Computing"),
new Product("10GB USB Flash Drive",476134,11,87.59,"Computing"),
new Product("USB Numeric Keypad",876123,23,10.45,"Computing")
};//end products array
private Scanner input;
privatevoid getTotalValue(){//get the total inventory value
double tVal = 0.0;
for(int i=0;i<myProducts.length;i++){
tVal = tVal + myProducts[i].getValue();
}
System.out.printf("Total Inventory Value: $%.2f", tVal);
}//end getTotalValue method
privatevoid Asort(){
String[] nName =new String[myProducts.length];
for(int i=0;i<myProducts.length;i++){
nName[i] = myProducts[i].getName();
}
Arrays.sort(nName);
for(int i=0;i<nName.length;i++){
if(i==nName.length-1){
System.out.print(nName[i]);
}else{
System.out.print(nName[i]+", ");
}
}
}
privatevoid getInput(){//get user input to display item information when match within array and user input is found
//initialize variables
String Name ="";
int Sku = 0;
int Qty = 0;
double Price = 0.0;
String Category ="";
//initialize scanner
input =new Scanner(System.in);
Main myMain =new Main();//initialize main class to call a method from within
//loop to get input until quit or exit is entered
while(!Name.equalsIgnoreCase("quit") && !Name.equalsIgnoreCase("exit")){
myMain.Asort();//bring sorted list of item names to show to the user
System.out.println("\n\nEnter an Item Name from the list (quit to exit):\n");//ask for item Name
Name=input.nextLine();//get user input
for(int i=0;i<myProducts.length;i++)//loop around array length
{
SubProduct subProd =new SubProduct(Name, Sku, Qty, Price, Category);
if (Name.equalsIgnoreCase(myProducts[i].getName()))//if match is found from user input and array items...
{
System.out.print(myProducts[i].toString()+"\n");//execute the toString method from Product class
System.out.printf("Total Item Value: $%.2f\n", myProducts[i].getValue());//execute getValue method from Product class
System.out.println(subProd.getRestockingFee());
myMain.getTotalValue();//call total value method inside main class to calculate the TOTAL inventory value
//print two empty (blank) lines
System.out.println();
System.out.println();
}
}
}
}
/**
* @param args the command line arguments
*/
publicstaticvoid main(String[] args){
Main myMain =new Main();//initialize main class to call a method from within
myMain.getInput();//call to getInput method which is where the action goes on...
}
}
For some god forsaken reason, i can't seem to get the restocking fee thing to work. I have tried a number of variations to the code I have posted.... this is the simplest form of them all, i had many other things that did not work either... somehow I am extremely good at making broken java code... if anyone needs to break some code let me know! I need to fix this one up so any pointers will be appreciated.
Thanks in advance for any help offered in this thread and excuse the length of the post.>
[14102 byte] By [
Elvenelfa] at [2007-11-27 9:58:51]

you are oh so close. Remember just what SubProduct is.... it's a new class but it also IS a product. Wherever you have Product in your main, you can use instead,..... what?Think on this and you will find your answer. I guarantee it.
My first step would be to make a much smaller program that has only the bare minimum needed to realize the construct you're having trouble with, and if I were posting it for others to help me, I'd get rid of all comments except those that are necessary to explain weird parts of the code or higlight, "This is the line I'm talking about."
Some people (e.g., yours truly), absolutely HATE reading any more of somebody else's code than is absolutely necessary.
* It's never necessary (but not harmful) to explicitly state "extends Object.". Leave it out. It's clutter.
* Comments like "// product Name" and "// begin/end getters" convey no information. They're clutter. Lose them.
* Likewse "} // end some loop or method". If your nesting is so deep or your blocks so long that you need those comments, then it's time to refactor into smaller, easier to understand pieces with better-defined resonsibilities.
* Repeating "new Product" for a dozen or so products is pointless when showing your code to those who would help you. One item is probably sufficient, maybe two or three if you need multiple ones to show the problem. The rest is just clutter.
> * It's never necessary (but not harmful) to
> explicitly state "extends Object.". Leave it out.
> It's clutter.
>
> * Comments like "// product Name" and "// begin/end
> getters" convey no information. They're clutter. Lose
> them.
>
> * Likewse "} // end some loop or method". If your
> nesting is so deep or your blocks so long that you
> need those comments, then it's time to refactor into
> smaller, easier to understand pieces with
> better-defined resonsibilities.
>
> * Repeating "new Product" for a dozen or so products
> is pointless when showing your code to those who
> would help you. One item is probably sufficient,
> maybe two or three if you need multiple ones
> to show the problem. The rest is just clutter.
Ok, I'll keep that in mind to reduce the clutter... also try to get in my shoes for a second before throwing all those advices head on... I am new to this... to me... ALL OF IT IS CLUTTER. I am used to doing PHP, and just to make a small comparative... 20 lines of good formatted code in PHP would transfer to 80 or more lines of code in JAVA... see where I am coming from? I have been hitting this head on for a while now... so just bear with me while I grasp the basics, learn the syntax and all that... In the meantime I will keep coming up with mental blocks and all sorts of stuff... I had no clue that commenting so much could be so ... annoying... But those are notes to self, and when u r in a hurry, it is HARD to go line by line deleting all those... cluttering comments.
Still, while I may question the way you made your point, I can understand that for people with more experience and larger egos too much code all at once for free help is kinda annoying...
> Still, while I may question the way you made your
> point, I can understand that for people with more
> experience and larger egos too much code all at once
> for free help is kinda annoying...
Ayiyii!.... are you trying to encourage jverd to help you or discourage him? Let me suggest a different tack.....
> > Still, while I may question the way you made your
> > point, I can understand that for people with more
> > experience and larger egos too much code all
> at once
> > for free help is kinda annoying...
>
> Ayiyiyiyiyiiii!!!.... are you trying to encourage
> jverd to help you or discourage him? Let me suggest
> a different tack.....
I honestly do not think he would help me at all... more or less his two posts were to let me know how to post... I had already posted. He did not mention much about help.
Still I am thankful. Even if it did not look like it. It just hits you... when someone has experience helping others, it crashes against you when others come at you like that when you ask for help.... imagine filing a form at some bank... the teller denies to accept the form because there is an error in the form. The teller gives you a blank form once more, and tells u to fill it out but does not tell you much about your error... so... good luck figuring it all out...
See? Did I ever ask for someone to reformat or rewrite the code i posted? I asked for hints and/or help troubleshooting. Your hint on the other hand points me in the right direction, now I know where I can tweak my code and try to make it work.
As for the cluttering comments, I do not think they will change because as I said, they are notes to self... to better understand the code, i write those for myself so I can better see what I am doing... I do not have a JAVA parser in my head to look at the code and spot problems, not that anyone else in here has some inhuman ability like that... but... anyways, i leave those comments cuz I need em.
Maybe there is a list about posting requirements that I missed!? but hey... I could have posted all the code without the code tags... so I didnt do it so bad for a beginner didnt I? I am sure that it would have made him throw one more asterisk in that last post...
> Ok, I'll keep that in mind to reduce the clutter...
> also try to get in my shoes for a second before
> throwing all those advices head on.
I've been in your shoes. I know what it's like.
I'm trying to do two things: 1) Help you get better help faster here. 2) Make my life and others' easier when reading your code.
> while now... so just bear with me while I grasp the
> basics, learn the syntax and all that... In the
> meantime I will keep coming up with mental blocks and
> all sorts of stuff... I had no clue that commenting
> so much could be so ... annoying... But those are
> notes to self, and when u r in a hurry, it is HARD to
> go line by line deleting all those... cluttering
> comments.
No problem. It's nothing personal. I'm just trying to inform and educate you. What you do with my comments is up to you.
> Still, while I may question the way you made your
> point, I can understand
Good. That's all I really ask.
> that for people with more
> experience and larger egos too much code all at once
> for free help is kinda annoying...
Ego has nothing to do with it. More like laziness and crankiness. :-)
> I honestly do not think he would help me at all...
> more or less his two posts were to let me know how to
> post... I had already posted. He did not mention much
> about help.
You may not see it, but his posts are being helpful. If you follow his advice, you stand a better chance of getting help, and not just from him.
> Still I am thankful. Even if it did not look like it.
> It just hits you... when someone has experience
> helping others, it crashes against you when others
> come at you like that when you ask for help....
Still, your ego should be strong enough to take it.
> imagine filing a form at some bank... the teller
> denies to accept the form because there is an error
> in the form. The teller gives you a blank form once
> more, and tells u to fill it out but does not tell
> you much about your error... so... good luck figuring
> it all out...
Big difference here. The teller and all the bank staff are being paid to serve you. Here you have nothing but volunteers. ANYTHING you can do, anything, that will make the volunteers job easier is highly recommended. jverd was pointing some hints to this effect, that's all.
> See? Did I ever ask for someone to reformat or
> rewrite the code i posted? I asked for hints and/or
> help troubleshooting.
You don't always get what you ask for on this site, but again, don't look gift horses in the mouth. My hint may seem helpful to you, but I agree with jverd that the format of your post is going to turn a lot of potential contributers off, including many who are A LOT smarter than I am. Please be grateful to jverd and his suggestions. If you follow them, you will stand a greater chance of getting useful help.
> As for the cluttering comments, I do not think they
> will change because as I said, they are notes to
> self... to better understand the code, i write those
> for myself so I can better see what I am doing... I
> do not have a JAVA parser in my head to look at the
> code and spot problems, not that anyone else in here
> has some inhuman ability like that... but... anyways,
> i leave those comments cuz I need em.
But for god's sake, take them out when you post your code. The first thing I did when I put your code into eclipse was to remove your infernal comments. They get in the way of my thinking. Realize that the code you post is not for you. It is for someone, anyone, who can possibly help you. Your job is to make their job easier. Remember that.
> Maybe there is a list about posting requirements that
> I missed!? but hey... I could have posted all the
> code without the code tags... so I didnt do it so bad
> for a beginner didnt I?
But again, your ego can stand this. This is not a criticism of you, but advice to help you get help.
Again, good luck!
> I honestly do not think he would help me at all...
I will if I find your problem interesting enough and easy enough to get to the heart of. Not that I mind a challenge--just that I want the challenge to be in solving the problem, not in figuring out what it is.
> Still I am thankful. Even if it did not look like it.
Cool. I really am not intending to be rude or b1tchy. Sometimes is just easier to cut the fluff and formalities and get right to the point.
> It just hits you... when someone has experience
> helping others, it crashes against you when others
> come at you like that when you ask for help....
Yes, I understand. If you saw the number of ill-thought-out posts from lazy idiots who only want someone else to do their work, you'd probably understand why some of us here can be rather blunt and curt sometimes.
> imagine filing a form at some bank... the teller
> denies to accept the form because there is an error
> in the form. The teller gives you a blank form once
> more, and tells u to fill it out but does not tell
> you much about your error... so... good luck figuring
> it all out...
That's not an analogous situation.
> See? Did I ever ask for someone to reformat or
> rewrite the code i posted? I asked for hints and/or
> help troubleshooting.
And you'll increase your chances of getting that if you make it easy for the people helping you to see to the heart of the matter. Plus there's the side benefit that by reducing the problem to its barest form, you'll figure it out for yourself. I can't tell you how many times that's happened to me. In the process of formulating my question clearly and concisely, I've had the answer hit me smack in the face and said, "...oh, nevermind, I just figured it out."
> As for the cluttering comments, I do not think they
> ...
> i leave those comments cuz I need em.
If you choose to leave them in your final code, that's your business. If you choose to leave them in code you post here, you're making it harder for the people whose help you seek to read your code. Your call, of course.
> Maybe there is a list about posting requirements that
> I missed!?
No. Some of it's common sense. Some is learned through experience--e.g. by having us ***** at you about it.
> but hey... I could have posted all the
> code without the code tags... so I didnt do it so bad
> for a beginner didnt I?
True dat.
> I am sure that it would have
> made him throw one more asterisk in that last post...
Yup. :-)
Heh... I must have two left hands... maybe thats why my code is not working... and that it also does not work most of the time >_<You guys are right. Point taken.
First on the comments/clutter business.
> I do not think they will change because as I said, they are notes to self... to better
> understand the code,
You're wrong. You posted them here: they are comments for others. And they don't help.
"To change this template, choose Tools | Template Manager...". That's a comment to yourself? to better understand the code? You're not even being genuine.
As has been mentioned, stating the obvious as a comment acts as noise and obscures rather than clarifies. Of course this is to some extent subjective. A comment like "//loop to get input until quit or exit is entered" might rate rather higher than following a for loop with "//loop around array length". Do you see why? The first states what a particular loop is designed to do. The second merely repeats what had already been written.
What is really missing from this code in terms of comments is a brief statement of what the classes represent, and what the methods are supposed to do. All we are left to work with is your observation "i can't seem to get the restocking fee thing to work". Anyone reading your post (but not your mind) is left bewildered: what is the "restocking fee thing"? and what is it for it to "work"?
(As another matter of style, please use lower case letters to begin variables. Classes are so integral to how Java works that using a meta-syntacic distinction between a variable and a Class in this way really helps.)
The code. A couple of thing jump out at you - although this post is so long that I'm probably late making them...
(1) In getInput() you create another Main object myMain. Why? getInput() is, itself a method of Main.
(2) More imprortantly is the SubProduct subProd that you create in this method. You print stuff about this product to the console. But, ask yourself: what values do you use to initialise this product with? That is, what are the values of the things you use as arguments to the SubProduct constructor?
Incidentally, regarding the hints I was mentioning, I was able to make those few changes and get your program to function correctly in just a few minutes. That's why I said you are close. Any progress yet?
> (2) More imprortantly is the SubProduct subProd that
> you create in this method. You print stuff about
> this product to the console. But, ask yourself: what
> values do you use to initialise this product with?
> That is, what are the values of the things you use
> as arguments to the SubProduct constructor?
I fully agree. Your implementation of SubProduct was way off base, and unnecessary.
> You guys are right. Point taken.See, we're not so bad once you get used to us. :-)
Well, the code as it stands now has more things than it is actually using. I was shooting for it to have two different restocking fees depending on the category... so computing items would have 15% and office supplies would have 5% restocking fees respectively.
Along my trial and error sessions... (i assure u they were too many) I kept adding and removing things... partially the reason why I ended up adding so many comments in the first place because I magically went confusing myself more and more to the point that nothing worked and then I chose to bring in the heavy cavalry ... and came here to ask for help.......
I see that it has been pointed about the implementation of subProduct.
In my first trials I had an if statement that would give me a different return depending on the value of this.category, but somewhere in there there was something wrong so I kept removing from that idea to the point that it is right now... i figured that If I couldnt make it the simple way... the harder more complex idea would not work either... which is a true scenario because none of the ideas worked and they all failed.
I am not too sure that I am doing it right with the subclass... I know I am using the right syntax... because it compiles and all that... but it is not working... data type errors would be caught by compiler right!? so... I dont know what I am doing wrong... it all kinda makes sense while I was writing it... but then when it did not work... I ended up clueless...
Anyway... I tried to change this line:
System.out.println(subProd.getRestockingFee());
OR it is in the sub class altogether... I am very uncertain...
> Anyway... I tried to change this line:> [code]System.out.println(subProd.getRestockingFee());[> /code]This attempt at implementing the subProd is wrong. Don't even try to correct it; get rid of it.
petes1234 may be right, and ultimately the solution may be found in changing (or deleting!) the SubProduct class.
But, less radically, the point I made was that you are calling the SubProduct constructor with very strange arguments. It compiles - but it's the values not the types that are wonky. Try this (inside the for loop):SubProduct subProd = new SubProduct(Name, Sku, Qty, Price, Category);
System.out.println("Using subProd");
System.out.println("Name=" + Name);
System.out.println("Sku=" + Sku);
System.out.println("Qty=" + Qty);
System.out.println("Price=" + Price);
System.out.println("Category=" + Category);
if (Name.equalsIgnoreCase(myProducts[i].getName()))
{
System.out.print(myProducts[i].toString()+"\n");
System.out.printf("Total Item Value: $%.2f\n", myProducts[i].getValue());
System.out.println(subProd.getRestockingFee());
myMain.getTotalValue();
System.out.println();
System.out.println();
}
Look at the printed output and see if you are invoking getRestockingFee() on the subproduct you mean to invoke it on.
[Edit] Hadn't seen the post above. I agree that the SubProduct class is a waste of time. Why can't Product have a getRestockingFee() method? Get the matching Product, call its getRestockingFee(), print the result. Job done.
hmmm... i know it would be easier if I did it all in the product class... but I wanted to learn about subclasses... so I tried dividing the load across product class and subproduct as a subclass...more or less I have not advanced much....
I disagree. You don't have to delete or change anything from Product or SubProduct. Have a look here at the difference between a Product array and a SubProduct array.
import java.text.NumberFormat;
public class TestProduct
{
private NumberFormat df = NumberFormat.getCurrencyInstance();
private Product[] myProducts =
{
new Product("Pencils", 528646, 312, 0.15, "Office Supplies"),
new Product("Pens", 673467, 233, 1.00, "Office Supplies"),
new Product("Markers", 245798, 112, 1.76, "Office Supplies"),
};
private SubProduct[] mySubProducts =
{
new SubProduct("Highlighter", 478469, 324, 1.95, "Office Supplies"),
new SubProduct("Eraser", 143100, 127, 0.10, "Office Supplies"),
new SubProduct("Tacks", 102701, 309, 1.00, "Office Supplies"),
};
public void showProduct()
{
System.out.println("Product Array Data:");
for (int i = 0; i < myProducts.length; i++)
{
String name = myProducts[i].getName();
double totalVal = myProducts[i].getValue();
System.out.println("total value of " + name + ": " + df.format(totalVal));
}
System.out.println();
System.out.println("SubProduct Array Data:");
for (int i = 0; i < mySubProducts.length; i++)
{
String name = mySubProducts[i].getName();
double totalVal = mySubProducts[i].getValue();
double restock = mySubProducts[i].calcRestocking();
System.out.print("total value of " + name + ": " + df.format(totalVal));
System.out.println("; restocking fee: " + df.format(restock));
}
}
public static void main(String[] args)
{
TestProduct tp = new TestProduct();
tp.showProduct();
}
}
They both can do the exact same things, except the subproduct array items can calculate a restocking fee while the product array items can't.
> petes1234 may be right, and ultimately the solution
> may be found in changing (or deleting!) the
> SubProduct class.
>
Actually, I didn't mean to imply that. Sorry. I meant his implimentation of SubProduct within his Main class (unforunate name for a class). We both agree that his current use of SubProduct within this class is way off base.
Message was edited by:
petes1234
Ok... I have bookmarked every thread. This has all been extremely enlightening, and I am very grateful for that.
Petes you were right when you said that it only required very little changes to make it work lol. I did have it all wrong when I was doing it with that line of code you all agreed that was wrong.
I took out all that implementation. And instead of declaring Product class, I declared SubProduct. Everything else worked just fine to my surprise... i expected like a thousand more errors... but inheritance did its part. lol.
Thanks a lot for your help. Now I got a stronger grasp on how these things work. I was really clueless. (not that I already know what everything is... but I feel like Neo... "whoa, I know king fu"). LOL
I moved from Product to subproduct the toString method... then added one or two more getters to Product to get the Sku and other stuff... I then added those changes along witht he restocking line to the toString method which lives inside subProduct by now.
Fixed the class declaration that has the array of new items... now it points to subProduct, removed the problematic implementation noticed in earlier posts and it works wonders now.
As I stated earlier, my gratitude knows no bounds guys, thanks a lot!
I'm happy that you have things working. Just a question: You didn't delete Product's toString, correct? Because the way to implement toString in SubProduct would be to use the parent's result:
@Override
public String toString()
{
return super.toString() + "\n" + getRestockingFee();
}
or something like that.
One other consideration: you may be safer to use
public static String newline = System.getProperty("line.separator");
in your program rather than "\n".
Thanks for the pointers Petes.
What I did was that I replaced the instance of Product when declaring it.
So instead of having an array of Product myProducts, i ended up giving myProducts into the SubProduct.
The toString method, i did not delete it, i moved the whole thing into SubProduct.
I saw that everything worked perfectly, and left it at that.
Is your suggestion for new lines a better practice for the use of GUI's? My next step for this code is to insert GUI. I figure its gonna be the swing thingy... i have very little practice, but I am sure I can make it work... I did a dummy program once that played around with user inputs... using the java swing object... or whatever it was called... i frankly dont remember...
EDIT: Ok, i am starting to get the hang of it. I added the GUI... it was done with the javax.swing.JOptionPane thing... ended up having to modify some stuff because the JOptionPane.showInputDialog() does not accept void type methods... so I made those void methods in my main class into strings and used String.format to pass it down into the dialogs with return... i am happy that I was able to do it without bothering anyone in here ;)
Message was edited by:
Elvenelf
