Share
Java Programming

Course Outline

Week 1
Week 2
Week 3
Week 4

Making Decisions

  • The if and if… else structures
  • Equivalency Operator
  • Nesting if and if … else statements
  • Using Logical AND and OR (&& and ||) Operators
  • Switch statement
Week 5
Week 6
Week 7
Week 8

SponsoredAdvertise

Explanations to week content

Conditional Statements

 

The if Structure

 

In Java, the simplest statement you can use to make a decision is the if statement. For example, suppose you have declared an integer variable named quizScore, and you want to display a message when the value of quizScore is 10. The following if statement makes the decision to produce output.

 

Note that the double equal sign ( == ) isused to determine equality


Figure: A Java Flowchart

 

Relational Operators

 

Operator Meaning
== Equal to
!= Not equal to
Less than
<= Less than or equal to
Greater than
>= Greater than or equal to
|| Or
&& And

 

The if … else Structure

 

Consider the following statement:

if(quizScore == 10)

System.out.println("The score is perfect");

 

Such a statement is sometimes called a single-alternative if because you only perform an action, or not, based on one alternative; in this example, you display a statement when quizScore is 10.Often, you require two options for the course of action following a decision. A dual-alternative if is the decision structure you use when you need to take one or the other of two possible courses of action. For example, you would use a dual-alternative if structure if you wanted to display one message when the value of quizScore is 10 and a different message when it is not.

 

In Java, the if … else statement provides the mechanism to perform one action when a Boolean expression evaluates as true, and to perform a different action when a Boolean expression evaluates as false.


 

    Figure: if … else structure

 

 Example

 

Write a program which ask the user to enter age. Your program should alert user “You are legible to drink” if the age is 18 or more and “You are not legible to drink” if age is less than 18


Sample Code


import java.util.Scanner;


public class main
{

      public static void main(String[] args) {
            // TODO Auto-generated method stub
            int age;
            //Get the age from the user
            Scanner inputDevice = new Scanner(System.in);
            System.out.println("Please enter your age");
            age = inputDevice.nextInt();
            inputDevice.nextLine();
            if(age>=18){
                  System.out.println("You are legible to drink");
            }else{
                  System.out.println("You are not legible to drink");

            }

      }

}


if … else with more than two options

If a decision could be based on more than two options, the following if … else statement is used

if(…){

   //option 1 is true

}else if(…){

  //option 2 is true

}else if(…){

 //option 3 is true

}

.else{

//None of the above options is true

}

 

Example


The following is the grading system of a school. Write an application to ask a user to enter the score. Your application should then compute the grade and output it to the user.

 

System

 

80 - 100 A
75 - 79 B+
70 - 74 B
65 - 69 C+
60 - 64 C
55 - 59 D+
50 - 54 D
Below 50 E

 

 

Sample Code


import
java.util.Scanner;

public class main
{
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            int score;
            //Get the age from the user
            Scanner inputDevice = new Scanner(System.in);
            System.out.println("Please enter your examination score");
            score = inputDevice.nextInt();
            inputDevice.nextLine();
            if(score>=80){
                  System.out.println("A");
            }else if(score>=75){
                  System.out.println("B+");
            }else if(score>=70){
                  System.out.println("B");
            }else if(score>=65){
                  System.out.println("C+");
            }else if(score>=60){
                  System.out.println("C");
            }else if(score>=55){
                  System.out.println("D+");
            }else if(score>=50){
                  System.out.println("D");
            }else{
                  System.out.println("E");
            }

      }

}


Nesting if and if … else Statements

 

Within an if or an else, you can code as many dependent statements as you need, including other if and else structures. Statements in which an if structure is contained inside another if structure are commonly called nested if statements. Nested if statements are particularly useful when two conditions must be met before some action is taken.

 

Example

 

For example, suppose you want to pay a Ghc50 bonus to a salesperson only if the salesperson

sells at least three items that total at leastGhc1,000 in value during a specified time. Write a program that ask a salesperson to enter number of items sold and the total amount of the items sold. And inform the salesperson whether qualified for the bonus or not.

 


Figure: Determining whether to assign a bonus using nested if statements


import
java.util.Scanner;


public class main
{
      public static void main(String[] args) {
            // TODO Auto-generated method stub

            int items;

            final int MIN_ITEMS = 3;

            final double MIN_VALUE = 1000;

            final double SALES_BONUS = 50;

            double amount;

            //Get the age from the user

            Scanner inputDevice = new Scanner(System.in);
            System.out.println("Please enter total items sold");
            items = inputDevice.nextInt();
            inputDevice.nextLine();
            //Check if the person has sold at least 3 items
            if(items>=MIN_ITEMS){
                  //Get the amount of items for the sold items

                  System.out.println("Please enter the total amount for the sold items");
                  amount = inputDevice.nextDouble();
                  inputDevice.nextLine();

                  //If the amount sold is more then minimum value to sell, give bonus else no bonus

                  if(amount>=MIN_VALUE){
                        System.out.println("You have a bonus of GHc "+SALES_BONUS);
                  }else{
                        System.out.println("You are not qualified for a bonus");
                  }

            }else{

                  System.out.println("You are not qualified for a bonus");

            }


      }

}


Using the switch Statement

 

By nesting a series of if and else statements, you can choose from any number of alternatives. For example, suppose you want to display a student’s class year based on a stored number.

 


Figure: Determining class status using nested if statements

 

An alternative to using the series of nested if statements shown in above is to use the switch statement. The switch statement is useful when you need to test a single variable against a series of exactinteger (including int, byte, and short types), character, or string values. The switch structure uses four keywords:


  • switch starts the structure and is followed immediately by a test expression enclosed in parentheses.
  • case is followed by one of the possible values for the test expression and a colon.
  • break optionally terminates a switch structure at the end of each case.
  • default optionally is used prior to any action that should occur if the test variable does not match any case.


 

 

 

Figure: Determining class status using a switch statement

 

 

Assignment

 

Write a program that asks the user to enter a number. Your program should display to the user whether the number is an even number or odd.

 

Design:

 

Enter a number > 3

3 is an odd number

 

SponsoredAdvertise