Surprisingly (unless you have been paying close attention), the output is:
No cookie for you.
if
Statements
However, you should not write a program that expects either
true or false with a floating point ==
operation.
There are many ways to use
the if
statement.
The statement can be used with one or two
branches, and a branch can have include one
or more statements.
The table that shows these variations.
The booleanExpression
in
each of these varieties evaluates to
true or false.
Boolean expressions come in a variety of forms,
which allow you to carefully state the conditions
under which each branch will execute (see the next
chapter for this.)
Varieties of if Statements | |
---|---|
if ( booleanExpression ) statement; |
if ( booleanExpression ) { one or more statements } |
if ( booleanExpression ) statement; else statement; |
if ( booleanExpression ) { one or more statements } else { one or more statements } |
if ( booleanExpression ) statement; else { one or more statements } |
if ( booleanExpression ) { one or more statements } else statement; |
The style of indenting used here leads to fewer errors than other styles you may have seen. An experiment with a group of professional programmers showed this to be true. Of course, the Java compiler ignores indenting and blank lines. Use this style unless there is a good reason not to (such as an employer or instructor that requires a different style.)
No matter which style you use, be consistent. Use the same number of spaces for indenting. (I use two spaces. Many people prefer four.) Soon you will be able to visuallize the logic of your programs. Programming and error catching will be easier.