Branching
In j
ava, an if test is basically the same as the boolean test in a
while
loop - except instead of saying, while there's still beer..",
you
will say, “ if there's still beer…."
class
IfTest (
public
static void main (String [] args) {
int x =
3;
i f
(x== 3) {
System.out.println(“
x must be 3” ) ;
}
System.out
.println( "This runs no matter what");
},
Output
:
x
must be 3
This
runs no matter what
The
code above executes the line that prints "x must be 3" only
if the
condition (x is equal to 3) is true. Regardless of whether
it's
true, though, the line that prints, "This runs no matter what"
will
run. So depending on the value of x , either one statement
or two
will print out.
But we
can add an else to the condition, so that we can
say
something like, "If there's still beer, keep coding, else
(otherwise)
get more beer, and then continue on…"
class
IfTest (
public
static void main (String [] args) {
int x =
2;
i f
(x== 3) {
System.out.println(“
x must be 3” ) ;
}
else{
System.out.println
(“x is not 3”) ;
}
System.out
.println( "This runs no matter what");
},
output
:
x
is not 3
This
runs no matter what
1 Comments
good
ReplyDelete