Be careful when you add statements to existing if
and if-else
statements. For example, let's say you had this code:
if (x == 1) System.out.println("x is 1"); else System.out.println("x is not 1");And then you decided you wanted to change your code so that if x is 1 then you want to set it to 2. You might change your code to look like this:
if (x == 1) System.out.println("x is 1"); x = 2; else System.out.println("x is not 1");Now, though, your code no longer compiles! You get the error message: "else without a matching if".
The problem is that both the if
and the else
expect
just a single statment to follow them. So when the compile sees the "x=2" statement,
it thinks it has seen the end of the if
statement. Your indentation
fools you into thinking that the if condition controls the execution of the
"x=2" statement, but it doesn't. Thus, by the time the compiler sees the "else",
there is no "if" for it to go with.
To fix the problem, treat the two statements following the if
clause as a single
statement. You do that with curly-brackets, forming a "block", or "compound
statement". (See pg. 212 in your textbook.) You need to rewrite your code as:
if (x == 1) { // Curly-brackets form blocks (compound statements) System.out.println("x is 1"); x = 2; } else // Don't need the curly-brackets here; there's just one statement System.out.println("x is not 1");
By the way, there's nothing wrong with using curly-brackets even if there is only one line of code in a block. An advantage of always using curly-brackets is that you can easily add other lines to a condition without forgetting to add the brackets.
if (x == 1) { // Curly-brackets form blocks (compound statements) System.out.println("x is 1"); x = 2; } else // Using brackets here, even though they're not required { System.out.println("x is not 1"); }