官术网_书友最值得收藏!

Conditional Statements

Conditional statements are used to control the flow of execution of the Java compiler based on certain conditions. This implies that we are making a choice based on a certain value or the state of a program. The conditional statements that are available in Java are as follows:

  • The if statement
  • The if-else statement
  • The else-if statement
  • The switch statement

The if Statement

The if statement tests a condition, and when the condition is true, the code contained in the if block is executed. If the condition is not true, then the code in the block is skipped and the execution continues from the line after the block.

The syntax for an if statement is as follows:

if (condition) {

//actions to be performed when the condition is true

}

Consider the following example:

int a = 9;

if (a < 10){

System.out.println("a is less than 10");

}

Since the condition a<10 is true, the print statement is executed.

We can check for multiple values in the if condition as well. Consider the following example:

if ((age > 50) && (age <= 70) && (age != 60)) {

System.out.println("age is above 50 but at most 70 excluding 60");

}

The preceding code snippet checks whether the value of age is above 50, but at most 70, excluding 60.

When the statement in the if block is just one line, then we don't need to include the enclosing braces:

if (color == 'Maroon' || color == 'Pink')

System.out.println("It is a shade of Red");

The else Statement

For some scenarios, we need a different block of code to be executed if the if condition fails. For that, we can use the else clause. It is optional.

The syntax for the if else statement is as follows:

if (condition) {

//actions to be performed when the condition is true

}

else {

//actions to be performed when the condition is false

}

Exercise 6: Implementing a Simple if-else Statement

In this exercise, we are going to create a program that checks whether bus tickets can be book based on the number of empty seats. Complete the following steps to do so:

  1. Right-click the src folder and select New | Class.
  2. Enter Booking as the class name, and then click OK.
  3. Set up the main method:

    public class Booking{

    public static void main(String[] args){

    }

    }

  4. Initialize two variables, one for the number of empty seats and the other for the requested ticket numbers:

    int seats = 3; // number of empty seats

    int req_ticket = 4; // Request for tickets

  5. Use the if condition to check whether the requested ticket numbers are lower than or equal to the empty seats available, and print the appropriate messages:

    if( (req_ticket == seats) || (req_ticket < seats) ) {

    System.out.print("This booing can be accepted");

    }else

    System.out.print("This booking is rejected");

  6. Run the program.

    You should get the following output:

    This booking is rejected

The else-if Statement

else if statements are used when we wish to compare multiple conditions before the else clause is evaluated.

The syntax for the else if statement is as follows:

if (condition 1) {

//actions to be performed when condition 1 is true

}

else if (Condition 2) {

//actions to be performed when condition 2 is true

}

else if (Condition 3) {

//actions to be performed when condition 3 is true

}

else if (Condition n) {

//actions to be performed when condition n is true

}

else {

//actions to be performed when the condition is false

}

Exercise 7: Implementing the else-if Statements

We are building an e-commerce application that calculates the delivery fee based on the distance between the seller and the buyer. A buyer purchases an item on our website and enters the delivery address. Based on the distance, we calculate the delivery fee and display it to the user. In this exercise, we are given the following table and need to write a program to output the delivery fee to the user:

Table 3.1: Table showing the distance and its corresponding fee

To do this, perform the following steps:

  1. Right-click the src folder and select New | Class.
  2. Enter DeliveryFee as the class name, and then click OK.
  3. Open the created class, and then create the main method:

    public class DeliveryFee{

    public static void main(String[] args){

    }

    }

  4. Within the main method, create two integer variables, one called distance and another called fee. The two variables will hold the distance and delivery fees, respectively. Initialize the distance to 10 and the fee to zero:

    int distance = 10;

    int fee = 0;

  5. Create an if block to check the first condition in the table:

    if (distance > 0 && distance < 5){

    fee = 2;

    }

    This if statement checks whether the distance is above 0 but below 5 and sets the delivery fee to 2 dollars.

  6. Add an else if statement to check the second condition in the table and set the fee to 5 dollars:

    else if (distance >= 5 && distance < 15){

    fee = 5;

    }

  7. Add two more else if statements to check for the third and fourth conditions in the table, as shown in the following code:

    else if (distance >= 15 && distance < 25){

    fee = 10;

    }else if (distance >= 25 && distance < 50){

    fee = 15;

    }

  8. Finally, add an else statement to match the last condition in the table and set the appropriate delivery fee:

    else {

    fee = 20;

    }

  9. Print out the value of the fee:

    System.out.println("Delivery Fee: " + fee);

  10. Run the program and observe the output:

    Delivery Fee: 5

Nested if Statements

We can have if statements inside other if statements. This construct is called a nested if statement. We evaluate the outer condition first and if it succeeds, we then evaluate a second inner if statement and so on until all the if statements have finished:

if (age > 20){

if (height > 170){

if (weight > 60){

System.out.println("Welcome");

}

}

}

We can nest as many statements as we wish to, and the compiler will evaluate them, starting from the top going downward.

switch case Statements

The switch case statements are an easier and more concise way of doing multiple if else statements when the same value is being compared for equality. The following is a quick comparison:

A traditional else if statement would look like this:

if(age == 10){

discount = 300;

} else if (age == 20){

discount = 200;

} else if (age == 30){

discount = 100;

} else {

discount = 50;

}

However, with the same logic, when implemented using a switch case statement, it would look as follows:

switch (age){

case 10:

discount = 300;

case 20:

discount = 200;

case 30:

discount = 100;

default:

discount = 50;

}

Notice how this code is more readable.

To use a switch statement, first you need to declare it with the keyword switch, followed by a condition in parentheses. The case statements are used to check these conditions. They are checked in a sequential order.

The compiler will check the value of age against all the cases and if it finds a match, the code in that case will execute and so will all the cases following it. For example, if our age was equal to 10, the first case will be matched and then the second case, the third case, and the default case. The default case is executed if all the other cases are not matched. For example, if age is not 10, 20, or 30, then the discount would be set to 50. It can be interpreted as the else clause in if-else statements. The default case is optional and can be omitted.

If age was equal to 30, then the third case would be matched and executed. Since the default case is optional, we can leave it out and the execution will end after the third case.

Most of the time, what we really wish for is the execution to end at the matched case. We want it to be so that if the first case is matched, then the code in that case is executed and the rest of the cases are ignored. To achieve this, we use a break statement to tell the compiler to continue to execute outside the switch statement. Here is the same switch case with break statements:

switch (age){

case 10:

discount = 300;

break;

case 20:

discount = 200;

break;

case 30:

discount = 100;

break;

default:

discount = 50;

}

Because the default is the last case, we can safely ignore the break statement because the execution will end there anyway.

Note:

It is good design to always add a break statement in case another programmer adds extra cases in the future.

Activity 6: Controlling the Flow of Execution Using Conditionals

A factory pays its workers $10 per hour. The standard working day is 8 hours, but the factory gives extra compensation for additional hours. The policy it follows to calculate the salary is like so:

  • If a person works for less than 8 hours – number of hours * $10
  • If the person works for more than 8 hours but less than 12 – 20% extra for the additional hours
  • More than 12 hours – additional day's salary is credited

Create a program that calculates and displays the salary earned by the worker based on the number of hours worked.

To meet this requirement, perform the following steps:

  1. Initialize two variables and the values of the working hours and salary.
  2. In the if condition, check whether the working hours of the worker is below the required hours. If the condition holds true, then the salary should be (working hours * 10).
  3. Use the else if statement to check if the working hours lies between 8 hours and 12 hours. If that is true, then the salary should be calculated at $10 per hour for the first eight hours and the remaining hours should be calculated at $12 per hour.
  4. Use the else block for the default of $160 (additional day's salary) per day.
  5. Execute the program to observe the output.

    Note

    The solution for this activity can be found on page 308.

Activity 7: Developing a Temperature System

Write a program in Java that displays simple messages, based on the temperature. The temperature is generalized to the following three sections:

  • High: In this case, suggest the user to use a sunblock
  • Low: In this case, suggest the user to wear a coat
  • Humid: In this case, suggest the user to open the windows

To do this perform the following steps:

  1. Declare two strings, temp and weatherWarning.
  2. Initialize temp with either High, Low, or Humid.
  3. Create a switch statement that checks the different cases of temp.
  4. Initialize the variable weatherWarning to appropriate messages for each case of temp (High, Low, Humid).
  5. In the default case, initialize weatherWarning to "The weather looks good. Take a walk outside".
  6. After you complete the switch construct, print the value of weatherWarning.
  7. Run the program to see the output, it should be similar to:

    Its cold outside, do not forget your coat.

    Note

    The solution for this activity can be found on page 309.

主站蜘蛛池模板: 华坪县| 青川县| 将乐县| 敖汉旗| 罗定市| 永善县| 麻阳| 巩留县| 双辽市| 腾冲县| 华宁县| 台江县| 苍溪县| 福鼎市| 双辽市| 香格里拉县| 财经| 杂多县| 石泉县| 章丘市| 乌审旗| 佛坪县| 乌审旗| 长沙县| 星座| 西平县| 新河县| 灵川县| 大兴区| 乐清市| 碌曲县| 滁州市| 德格县| 西青区| 三门县| 湘潭市| 湟源县| 增城市| 澄城县| 定远县| 当阳市|