• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can someone please help explaining while loops and conditional breaks?  RSS feed

 
Daniel Ungerfält
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hi there folks!

Just starting to learn java and have a question about programs like these.
I just want to know how to count this lines of codes. Because if I place for example i++ further up the code or the system.out.println a bit lower the result will be 1-49 or 2-50 and not the goal that is 1-50.
I want to know how to think and count. Why do i get 2345678.........50 and not 12345678........50 or 12345678.....49, thats the question.
Sorry for a messy text.
 
Tony Docherty
Bartender
Posts: 3271
82
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

I've edited your post to add code tags and remove some of the empty lines to make it easier to read. Using proper indentation would also help but I'll leave that up to you to do.

As to your question get a pencil and some paper and work through the code line by line executing the code in your head and each time i is set to a value or is incremented write down the new value of i and each time System.out.println is encountered on second piece of paper write down the value that will be output. Now move the i++ to the other position you talked about and do the same again. BTW You may want to set the upper limit to 5 rather than 50 or you will have a lot of writing to do.
 
Mark King
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the beginning you initialize i to 1. Now if you you put i++ before the println, i will equal 2. But if you put i++ between the println and the if clause, on the last run of your loop, i will be 49 when reaching the println, i will increase and will now be 50 the condition in the if clause is met, break; executes and 50 is never printed.

BTW you can get rid of the if clause by changing the while loop to check if i is greater or equal to 50.
 
Daniel Ungerfält
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for this quick respons! :-)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!