Error when assigning booleans | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Error when assigning booleans

I started learning Java here yesterday, and I wanted to try to make FizzBuzz in java (https://www.youtube.com/watch?v=QPZ0pIK_wsc). When I assign a boolean and then test it things seem to go fine, but whenever I assign a boolean if another condition is true/false, I get the errors 'cannot find symbol' and 'illegal start of type' for every time I check if the boolean is true. This is my code: class SomeClass { public static void main(String[ ] args) { for (int i = 1; i <= 100; i++){ if (i % 3 == 0){ boolean multOfThree = true; } else{ boolean multOfThree = false; } if (i % 5 == 0){ boolean multOfFive = true; } else{ boolean multOfFive = false; } if (multOfThree){ if (multOfFive){ System.out.println("FizzBuzz"); } else{ System.out.println("Fizz"); } } else{ if (multOfFive){ System.out.println("Buzz"); } else{ System.out.println(i); } } } } }

21st Nov 2017, 8:03 PM
Fabian de Korver
Fabian de Korver - avatar
4 Answers
+ 6
the problem is thatyou declare boolean inside each if statement. and you need to do it once. it's like you want to put glass inside a glass (same kind of glass). but in fact the only thing you can change is that if glass is empty or not. so declare boolean multOfThree; before first if statement and later use just multOfThree (for example multOfThree = true;) do you get it?
21st Nov 2017, 8:17 PM
Bartek Nowacki
Bartek Nowacki - avatar
+ 5
When a variable is declared inside a block of code such as an if statement, the variables scope is within that block. Meaning, it cannot be accessed outside the if statement. Example: if (true){ int a = 5; } System.out.println(a); // ERROR, Cannot find symbol 'a' You are using multOfFive outside its scope. So, you must enlarge its scope. Declare the variable outside the if statement like so: boolean multOfFive = false; if (i % 5 == 0) multOfFive = true; // etc.... /* Could also write: boolean multOfFive = (i % 5 == 0); Now the if statement isn't needed. */ Same thing with multOfThree. While we do want to keep variables in the smallest scope possible, we had good reason to enlarge the scope here. I.E: so we can access it from the other if statements.
21st Nov 2017, 8:20 PM
Rrestoring faith
Rrestoring faith - avatar
0
Thanks!
21st Nov 2017, 8:29 PM
Fabian de Korver
Fabian de Korver - avatar
20th Feb 2021, 5:55 AM
Kailash Singh
Kailash Singh - avatar