|
|
|||||||||
|
|||||||||
|
|||||||||
| |
|||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Help on a Programming Problem :)
Hey guys. Im working on this question and im getting thrown completely becuase i dont understand how it is getting the answers shown below the code.... I have narrowed it down to the this.n.. if someone could please explain how the this.n is effecting the program and why it comes out with these answers id be so greatful.
public class Foo { int n; static int m = 0; public Foo(int n) { this.n = 2 * n + m; m++; } public void calc(int n) { System.out.println(n); System.out.println(this.n); System.out.println(m); this.n = n * this.n + n * m; } public static void main(String[] args) { Foo n = new Foo(2); Foo m = new Foo(3); n.calc(m.n); m.calc(n.n); System.out.println("n's n is " + n.n); System.out.println("m's n is " + m.n); System.out.println("The value of m is " + Foo.m); } } ANSWERS : n's n is 42 m's n is 378 The value of m is 2 Help Please ![]() |
|
#2
|
||||
|
||||
|
Complaint: use better variable names... especially not M and N as oject names if they're used inside the class itself as well! =)
In fact, that might mess things up... be careful. The code is unbelievely hard to follow Should member variable n be declared as public? What values do you expect to see? What are the actual System.out.print in the calc method displaying?
__________________
Daryl's Homepage | My Blogroll | My Profile | Firefox supporter! DevArticles Forum Moderator "The net is a waste of time, and that's exactly what's right about it." -- William Gibson |
|
#3
|
||||
|
||||
|
this.n always points to the instance variable. This piece of code repeatedly shadows it's own variables (shadowing is the official term
) which is not good practice! |
|
#4
|
||||
|
||||
|
I quite like the answers in this thread...
It's a shame Jenkins never followed up on his post. |
|
#5
|
||||
|
||||
|
heh, funny you should say that...
I had that exact same though after reading the inital post earlier today. |
|
#6
|
||||
|
||||
|
Yeah
I recently passed the Sun java programmer certificate and this code example looks very much like the questions on that exam.. Very tricky, far fetched, and generally not-good java programs but excellent exam questions.. |
![]() |
| Viewing: Dev Articles Community Forums > Programming > Java Development > Help on a Programming Problem :) |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|