This week's book giveaway is in the Testing forum.We're giving away four copies of The Way of the Web Tester: A Beginner's Guide to Automating Tests and have Jonathan Rasmusson on-line!See this thread for details.
Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Need help understanding puzzle from Head First Java p91

Dan Laidlow
Greenhorn
Posts: 4
Hoping someone can help me understand the following code from Head First Java. I managed to solve the puzzle through much trial and error however I still don't quite understand how it is coming to the result displayed in the solution. The console returns the text "Result: 543345" when I run the package but I'm getting completely lost following the maths. Really want to understand what is happening here before I move on in the book in case I've missed something, can someone enlighten me?

From my maths the "ivar" variable should have a value of 100000 by the time the first while loop exits but that doesn't seem to add up properly. Have pasted codes from both class files below if someone cares to take a look, did a bit of searching around online to see if I could find more info but they were all help solving the project rather than explaining the code itself. Cheers!

Campbell Ritchie
Sheriff
Posts: 50700
83
• 1
Welcome to the Ranch

I haven’t got my page 91 (or any of the other pages) to hand at the moment, so I can’t confirm that you have copied the code correctly.
What they want you to do is go through the code with a pencil and paper. Find whoever said you would not need pencil and paper again, and shoot them. Then write down the initial values of x yIf you add columns for ivar*factor and ivar*(5-factor) you can add those values up and I hope get 543345. That is the idea behind those puzzles: to get you used to following that value of variables as execution proceeds.

Dan Laidlow
Greenhorn
Posts: 4
Cheers for that, I actually tried doing it on paper earlier but must have got my wires crossed. This time I did it and it all clicked into place in my mind, totally understand it now!

Thanks

Campbell Ritchie
Sheriff
Posts: 50700
83
Well done