Jump to content

Java:Tutorial - Flow Control

- - - - -

  • Please log in to reply
1 reply to this topic

#1
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
  • Location:New York, NY
There are three main types of flow controls. The if...else statements, the switch statements, and the do…while statements which I have already discussed in the loops tutorial. Probably the most common is the if…else statement which you learn about in junior high school.

The basic idea behind the if statement is

if(true){
//evaluate code
}

Which is absolutely necessary if you want your program to make any decisions. Between the parentheses a Boolean statement is evaluated, if it is true it will evaluate the code, in this example if it is false it will totally ignore it. What is a Boolean statement you ask? A Boolean statement can be written using any logical operator. For example:

int x = 0;
if(x == 0){
//evaluate code
}

Will evaluate the code. Java also has the cabapility to evaluate code if the if statement is false. To do that you will use the else clause.

int x = 1;
if(x == 0){
//evaluate code
}else {
//evaluate code
}

In this case, when the if statement is evaluated, it returns false and then the else code is executed. To allow even more flexibility, Java has an else if statement also.

int day = 2;
if(day == 1){
System.out.println(“Monday”);
}else if(x == 2 {
System.out.println(“Tuesday”);
} else {
//evaluate code
}

Although this is extremely useful, depending on what you need to do, there is a more efficient way, the case/switch mechanism. For the example above, to write five more else if statements would work to determine the day of the week but it could be more efficient to create something like this:

int day = 2;
switch (day) {
case 1:  System.out.println("Monday"); break;
case 2:  System.out.println("Tuesday"); break;
case 3:  System.out.println("Wednesday"); break;
case 4:  System.out.println("Thursday"); break;
case 5:  System.out.println("Friday"); break;
case 6:  System.out.println("Saturday"); break;
case 7:  System.out.println("Sunday"); break;
}


#2
Bitterfrost

Bitterfrost

    Newbie

  • Members
  • Pip
  • 1 posts
Hi,

There is an error in the code:

int day = 2;
if(day == 1){
System.out.println(“Monday”);
}else if(x == 2 {
System.out.println(“Tuesday”);
} else {
//evaluate code
}

}else if(x == 2 has to be }else if(day == 2)




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users