• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can someone help me with this simple problem? (head first java exercise)  RSS feed

 
Tyler Taylor
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, hello everybody! I have recently gotten the programming itch. In googling questions, this site popped up a bunch so I figured I might as well join.

Take it easy on me, I am a complete greenhorn!

Okay so I just got to the first exercise of Head First Java, and I'm slightly confused by the output I'm getting. They give you snippets of code that are supposed to be magnets on a fridge, out of order, and you have to put them in order. Pretty simple!

It SHOULD be "a-b c-d", but I am getting "a-b c-d-" and can't figure out how to get rid of the last hyphen.

It is probably very obvious haha but my newb eyes can't see it. If x is equal to 1, it prints "d"; but the while loop is x greater than 0, so since D/1 is still > 0 it's printing the hyphen at the end? Am I right in that?

Thanks for any help! Hopefully soon I can contribute and help too.

Here's the code:
 
Tyler Taylor
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
LOL oh wow, the answer was a few pages after the exercise, so I feel dumb for posting. But I'm still not entirely sure what changed the last hyphen. Maybe someone could explain it in cavemen terms for me?

I moved the x = x - 1 and print up, then added another x = x - 1 to the last if statement. Why is that necessary after the first one?

Here is the correct code:
 
Sachin Tripathi
Ranch Hand
Posts: 368
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The last x=x-1 is used to come out of the while loop
 
Emil Jennings
Ranch Hand
Posts: 75
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the first iteration at line 7 the value of x is 3, so line 9 is true and it prints a. Line 13 executes and the value of x becomes 2, then - is printed. Line 16 is true and b c is printed. Line 20 is false and the loop starts over.

In the second iteration x is 2 so line 9 is false. Line 13 executes and the value of x becomes 1, then - is printed. Line 16 is false. Line 20 is true and d is printed and the value of x becomes 0. And back to the loop condition.

In the third iteration the loop condition is met and the loop exits. If the second x = x - 1 wasn't coded the loop would have executed one more time and the additional - would be printed after the d.
 
Tyler Taylor
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much Emil, that really helped me understand.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!