Results 1 to 5 of 5
- 12-01-2011, 08:35 PM #1
Member
- Join Date
- Sep 2011
- Posts
- 45
- Rep Power
- 0
Help with printing simple things.
So I have this simple code with various methods and I need to determine the state of the object after each line.
For example after line 22, bee refers to Trace in which a = 1, and zoo refers to Trace in which a = 3. Right? Or am I wording this wrong?Java Code:public class Trace { private int a; public Trace(int a){ this.a = a; } public Trace(int a, int b) { this.a = a * b; } public int joe(int a) { return this.a += a; } public int liz(int a ) { return this.a *= a; } public static void main(String[] args) { Trace bee = new Trace(1); Trace zoo = new Trace(3); bee.joe(2); bee.liz(2); zoo = bee; bee = new Trace(2,4); zoo.joe(bee.liz(2)); bee = zoo; bee.liz(3); } }
How would I print these values for each line to test if my predictions are correct?
I try printing bee and zoo but that doesn't seem to work...
ACTUALLY,
I managed to print out each step by using System.out.println(bee.a); and System.out.println(zoo.a);
But I am confused as to how I got each value.
Can someone explain why putting in bee.joe(2); gives an output of 3? Maybe I can be able to get it from there.Last edited by Aimforthehead; 12-01-2011 at 08:44 PM.
- 12-01-2011, 09:39 PM #2
Moderator
- Join Date
- Jul 2010
- Location
- California
- Posts
- 1,608
- Rep Power
- 5
Re: Help with printing simple things.
Take a pen and paper and write out each step the program performs one by one. You create an object with a variable a value of 1, you then call the method joe - which adds the parameter 2 to a (this equals 3) and sets the value of a to this result, and finally return the result.Can someone explain why putting in bee.joe(2); gives an output of 3?
- 12-01-2011, 10:35 PM #3
Member
- Join Date
- Sep 2011
- Posts
- 45
- Rep Power
- 0
Re: Help with printing simple things.
Well, I did that first and came out with 5. I thought
Trace zoo = new Trace(3); would give a the value of 3, then in joe(2) it adds that with 2...why does it add 1 with 2 and not 3 with 2?
- 12-01-2011, 11:21 PM #4
Re: Help with printing simple things.
Because you are calling the joe method on the bee object which contains 1 (1 + 2 = 3) not the zoo object which contains 3.
- 12-02-2011, 01:01 AM #5
Member
- Join Date
- Sep 2011
- Posts
- 45
- Rep Power
- 0
Similar Threads
-
Simple text printing with pagebreaks
By miloshz in forum AWT / SwingReplies: 0Last Post: 05-10-2011, 05:34 PM -
Need Help. with two simple things
By Fred1 in forum New To JavaReplies: 32Last Post: 04-28-2011, 02:35 AM -
Couple hopefully simple things.
By drucey in forum New To JavaReplies: 10Last Post: 11-18-2010, 08:44 PM -
printing simple text as text on printer
By Nicholas Jordan in forum Advanced JavaReplies: 0Last Post: 12-01-2008, 01:42 AM -
Simple Printing Example
By Java Tip in forum SWTReplies: 0Last Post: 07-11-2008, 04:41 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks