This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
But the code below with the brackets surrounding the whole right hand side works. Why ? I thought for b = b-(b/2); Java will just execute the brackets 1st (b/2) , and then execute the b which is outside the brackets ?
If what you are trying to do is output all numbers from 16 down that can be divided by 2 then your problem lies in the line of code that is in the brackets beside the keyword 'while'. I ran the code the way you wrote it and with both examples I got an endless output of 1's. Kind of hypnotizing to watch. I made one tiny correction (as well as adding a closing bracket that your example is missing, probably from when you copied and pasted) and both examples output 16 8 4 2. I don't see how your second example could have worked the way you show it. Unless you wanted to see a hynotizing screen full of ones, which is not a bad thing. Anyway, look at the argument that controls your while loop.
WeiJie Lim wrote:[
Oh thanks I think I get it. For the formula b = (b-(b/2)) , it will be stuck in an infinite loop when b=1 as b = (1-(1/2)) = (1-0) = 1 .
Is this the reason ?
Well, yes, it's true that b = (b-(b/2)) when b is 1 is b = (1-(1/2)) = (1-0) = 1. As to whether that causes an infinite loop or not, it depends on your loop condition. In your particular, case, since your loop condition was while (b >=1), yes, that combination led to an infinite loop.
subject: The use of brackets in mathematical equations.