Results 1 to 4 of 4
Thread: c always equals a*b
- 11-11-2010, 08:43 PM #1
Senior Member
- Join Date
- Aug 2010
- Posts
- 127
- Rep Power
- 0
c always equals a*b
My question is if it's possible to make a variable dependant on other variables. I want write a program where I am going to frequently use the answer of variable "a" times varbiable "b" (both int's). This means often typing "a*b". My question is if it is possible to make a variable "c" that is always equal to "a*b". Whenever "a" or "b" is changed, "c" would also change. This would be great for reducing potential for error and make for neater code. But is it possible?
- 11-11-2010, 08:52 PM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,545
- Rep Power
- 11
You could have a class with member variables a and b and a method getProduct() which returns their product. The class could be implemented in whatever way makes sense for your application: for instance if the product is accessed ofte and the values set only rarely you might want to precalculate the product in the methods that set the variables' values.
A more complex approach would be for a and b to be instances of a class which fires an event when its value changes. The product could then be an instance of a class which listens for such changes and figures out its value appropriately.
This would be great for reducing potential for error and make for neater code.
But if the aim is merely saving keystrokes my suggestions may be wide of the mark.
- 11-11-2010, 08:52 PM #3
Senior Member
- Join Date
- Mar 2009
- Posts
- 552
- Rep Power
- 5
Its possible, indirectly, but usually not done. It requires an additional class field that is updated whenever a or b is changed (to cache the result of a*b).
You're probably better off sticking with a*b.
EDIT: Beaten by pbrockway, but my point still stands.If the above doesn't make sense to you, ignore it, but remember it - might be useful!
And if you just randomly taught yourself to program, well... you're just like me!
- 11-12-2010, 02:32 PM #4
You could make a method which calculates a*b and sets c equal to it and then just call the method, every time, the varibles get changed.
Check out my youtube: http://www.youtube.com/user/MyrtleTheGhost
and also: http://www.youtube.com/user/ExplosionXTreme
Similar Threads
-
Int equals void
By Insomniac Riot in forum New To JavaReplies: 14Last Post: 05-06-2010, 03:44 PM -
need help using equals methods
By ShinTec in forum Advanced JavaReplies: 3Last Post: 04-05-2010, 03:19 AM -
== and equals()
By arefeh in forum New To JavaReplies: 13Last Post: 01-05-2010, 04:56 PM -
== is same as .equals()??
By DrMath in forum New To JavaReplies: 1Last Post: 09-30-2009, 04:57 AM -
name clash: equals(E) in and equals(java.lang.Object)
By AdRock in forum New To JavaReplies: 0Last Post: 01-25-2008, 11:13 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks