Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Head First Java - Chapter 4 puzzle question

 
William Wyatt
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to understand the pool puzzle problem on page 91 and hoping that someone can give me a hand. I can't figure out how the integer (ivar) gets any value assigned to it other than 0 and I can't understand how it works with 0 as the value. Below is a copy of the code.

public class Puzzle4 {
public static void main(String[] args) {
Puzzle4b[] obs = new Puzzle4b[6];
int y = 1;
int x = 0;
int result = 0;
while (x < 6) {
obs[x] = new Puzzle4b();
obs[x].ivar = y;
y = y * 10;
x = x + 1;
}
x = 6;
while ( x > 0 ) {
x = x - 1;
result = result + obs[x].doStuff(x);
}
System.out.println("result " + result);
}
}
class Puzzle4b {
int ivar;
public int doStuff(int factor) {
if (ivar > 100) {
return ivar * factor;
}else{
return ivar * ( 5 - factor );
}
}
}

p.s. This is my third head first book and I love them all.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

Just looking at the Puzzle4b class by itself, you don't see the variable being assigned to anywhere. But look at Puzzle4, and you see

obs[x] = new Puzzle4b();
obs[x].ivar = y;

these two lines create a Puzzle4b instance, and set the value of ivar in that instance. Later, when obs[x].doStuff(x) is called, the Puzzle4b instance in obs[x] still has that nonzero value of ivar.
 
William Wyatt
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much, especially for the quick response. It seems so obvious now, don't know why I didn't see it before. Thanks again.
 
William Wyatt
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One more quick question, in this section:

while ( x > 0 ) {
x = x - 1;
result = result + obs[x].doStuff(x);
}
System.out.println("result " + result);
}
}

Will the while loop run when x is equal to 0?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nope.
 
samir Sadiki
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it won't but x will receive the value 0 when you enter the loop at x=1, because of the line x=x-1.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic