• Post Reply Bookmark Topic Watch Topic
  • New Topic

an effort of avoiding hardcode  RSS feed

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have encountered a problem in my simulation project wherein I have been left with no choice but to hard-code an important aspect of the algorithm. This, essentially, implies that I have to write down numerous lines of code which otherwise could have been avoided using a control structure (for instance, a for loop). I, in fact, gave the for loop a shot but it failed miserably. This following two classes work together to cause the motion of three rectangles from the top to the bottom of the frame. But what if I need 20 rectangles to move from the top of the frame to the bottom? Would that mean I have to write 17 more of these:



Isn't there anyway around it?

Here are the classes:



And this is the PaintJob class. It is obvious what it does:




 
Saloon Keeper
Posts: 4036
94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why would you need to write 20 lines of code? Can't you keep the parameter values in some kind of data structure that you can iterate over?
 
Bartender
Posts: 1558
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi vasiq shair,

Welcome to CodeRanch!

The part in which you want to avoid hard-coding (line 28 to 30) could be simply done as following:
1) Iterate over the vector (instead of manually saying vet.get(1) etc.)
2) Put those x1, y1 etc. in an array.
3) Make sure that length of vector is same as length of co-ordinate array (otherwise you'll have to handle that scenario).

I hope this helps.
 
vasiq shair
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would you be kind enough to give me an example?
 
Anayonkar Shivalkar
Bartender
Posts: 1558
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
vasiq shair wrote:Would you be kind enough to give me an example?

Well, I don't want to sound rude, but this is NotACodeMill.

The change is quite easy. As Tim Moores has already pointed out, you'll need a data structure and then iterate over it. You are already having Vector for PaintJob. You'll need another data structure to hold co-ordinates (x1, y1 etc.), so, I suggested to use an array (say 4 x length etc.)

You can proceed with those changes and get back if you face any problems

I hope this helps.
 
vasiq shair
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeap, the iterator solved it. Thank you so much for your input.
 
Anayonkar Shivalkar
Bartender
Posts: 1558
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are welcome
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!