+ 1

Why is my code outputting this?

Hi, I am very new to Solo Learn and Java in general, so I apologize if I posted this wrong or if my error is blatantly obvious. This is my code. public class Program { public static void main(String[] args) { boolean jq = true; boolean andrew = true; boolean jack = true; boolean finn = true; boolean jonathan = false; boolean sean = true; boolean jay = false; boolean danny = false; boolean ethan = false; int randoms = 0; int probability = 0; if(jq = true){ ++probability; }else if(jq = false){ probability=probability; } if(andrew = true){ ++probability; }else if(andrew = false){ probability=probability; } if(jack = true){ ++probability; }else if(jack = false){ probability=probability; } if(finn = true){ ++probability; }else if(finn = false){ probability=probability; } if(jonathan = true){ ++probability; }else if(jonathan = false){ probability=probability; } if(sean = true){ ++probability; }else if(sean = false){ probability=probability; } if(jay = true){ ++probability; }else if(jay = false){ probability=probability; } if(danny = true){ ++probability; }else if(danny = false){ probability=probability; } if(ethan = true){ ++probability; }else if(ethan = false){ probability=probability; } System.out.println(probability); } } My question is why is my code outputting 9 when only 5 of the booleans are true?

12th Jan 2019, 1:10 AM
Julian Quiroz
Julian Quiroz - avatar
2 Respuestas
+ 5
The one obvious fault here is the use of '=' instead of '=='. The former is the assignment operator, and the latter checks for equality.
12th Jan 2019, 2:38 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
For comparisons you should use the equal operator (==). Because you are using the assignment operator (=), all the conditions are true since the assignment is done correctly. So, probability is 9. By the way, you don't need to assign the value of probability in each 'else' condition, since it is not changing. You could do the following: if(some_expression == true) ++probability; if(some_other_expression == true) ++probability; ... and so on.
12th Jan 2019, 3:02 AM
Luciano Horvath
Luciano Horvath - avatar