+ 2

java boolean example

How this work? seems im not fully understand boolean boolean b = true; for(int i = 0;i < 11;i++) if(b = !b) System.out.print(i);

9th Jul 2019, 7:37 AM
Tzion
Tzion - avatar
9 ответов
+ 5
Like Drax said, when you have more than one statement in a block, you should wrap the block in a {} Without it, you risk having only the first statement following the for loop to be executed, while the rest of the statements are ignored, may not be what we want right? Initially <b> value was true ... ** Begin Loop. From 0 ~ 10 <i> = 0 `if(b = !b])` inverse <b> value true -> false since <b> is now false DO NOT print <i> <i> = 1 `if(b = !b])` inverse <b> value false -> true since <b> is now true print <i> <i> = 2 `if(b = !b])` inverse <b> value true -> false since <b> is now false DO NOT print <i> // And it goes on until <i> value became 10, // and by then ... ** Loop Ends I think this is how it works ... maybe ...
9th Jul 2019, 8:13 AM
Ipang
+ 3
Your code is wrong. Add parantheses on your for loop!
9th Jul 2019, 8:05 AM
Drax
Drax - avatar
+ 3
boolean b = true; for(int i = 0;i < 11;i++){ if(b == !b) System.out.print(i); }
9th Jul 2019, 8:06 AM
Drax
Drax - avatar
+ 2
Tibor Santa Check this out.... assignment operator = means equal but it can be change operator == means equal but it was fixed,unable to change. https://code.sololearn.com/c509deZh14oo/?ref=app
9th Jul 2019, 10:03 AM
Tzion
Tzion - avatar
+ 2
Sorry, didn't meant to be rude or anything 😂
9th Jul 2019, 10:46 AM
Drax
Drax - avatar
+ 2
Ok so it is not a typo then. If this is in the challenge then this is how it works. First b = true. Then you make a loop starting from 0 to 10. Within the if() condition you are actually changing b to its opposite: if(b=!b) this means: let the value of b be 'not b'. In the first iteration, this changes b to false. So it becomes: if(false) So in the first iteration when i==0 the if condition fails and nothing is printed. Each iteration flips b around, so the result is, only odd numbers are printed.
9th Jul 2019, 11:13 AM
Tibor Santa
Tibor Santa - avatar
+ 1
if(b = !b) this makes no sense... first, the comparison operator for equality is == (two equal signs) and even if you use that, b will never be equal to its negative because True is never False. so your print will never be executed.
9th Jul 2019, 8:43 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Drax bro,im just copied from quiz section...... take it easy , if wanna to correct it , parantheses is not enough,should add main method and classes 😂
9th Jul 2019, 9:58 AM
Tzion
Tzion - avatar
+ 1
Drax what !? no need to sorry , thanks for youe reminding btw
9th Jul 2019, 3:33 PM
Tzion
Tzion - avatar