+ 2

Pls, why does this code print only odd numbers in the range? And if I chnge the "if" to (x = x) it prints the full range

public class Program { public static void main(String[] args) { boolean x = true; for(int i = 0;i < 11;i++){ if(x = !x)//try change = to == System.out.println(i); } } } I'm used to (x==x) or (x==!x)

11th Dec 2019, 6:54 AM
ISOSIYA WARMATE
ISOSIYA WARMATE - avatar
7 odpowiedzi
+ 3
This code should most definetly not print anything, as you are repeatedly checking if true == false, which it never is. Can you try to write this code in sololearn's development environment and send it to me? Ill be of better help seeing your code in there instead of in the description.
11th Dec 2019, 8:07 AM
coddy
coddy - avatar
+ 3
try this boolean x = true; System.out.println(x = !x); //assign into x negation of x and print result System.out.println(x = !x); System.out.println(x = !x); System.out.println(x = !x);
11th Dec 2019, 8:13 AM
zemiak
+ 2
Coder's Crux Output: 1 3 5 7 9
11th Dec 2019, 9:12 AM
ISOSIYA WARMATE
ISOSIYA WARMATE - avatar
+ 2
Also, please, can I use "=" instead of "==" in checking boolean relational condition, e.g. "if(x = !x)" instead of "if(x == !x)"? I'm kinda new though, if the question sounds dumb
11th Dec 2019, 9:31 AM
ISOSIYA WARMATE
ISOSIYA WARMATE - avatar
+ 2
Line after if( expression ) is execute only if result of expression is true. x = 1; // mean: store into variable x value 1, then x is 1 x == 1 // mean question: Is 1 in x ? and answer is true or false !x // mean: if true is in x result is false if false is in x result is true if(x=true) is same as: x = true // store into x value true if(x) // if in x is true if(x = !x) is same as: x = !x // change value to opposite if(x) // if in x is true here you change value of x in order x: true //start value x: false true false true false i : 0 1 2 3 4 print 1 3 ...
11th Dec 2019, 2:06 PM
zemiak
+ 2
zemiak Coder's Crux Thanks to you guys, I get it now
11th Dec 2019, 4:28 PM
ISOSIYA WARMATE
ISOSIYA WARMATE - avatar
+ 1
zemiak I actually thought of it that way, but it prints odd numbers in the range i.e. The output is: 1 3 5 7 9 //terminate But the condition "if(i = !true)" works accordingly
11th Dec 2019, 9:11 AM
ISOSIYA WARMATE
ISOSIYA WARMATE - avatar