Home CPSC 220

Making Decisions

 

Overview

Frequently in programs, we need to have our program do different things depending on some decision. Many algorithms this.

For example, in the guess the number algorithms, we have to do different things based on whether we got the number right, were too high, or too low. Today we'll learn how to make decisions in Java programs.


 

If statements

The main way to make a decision in Java is with an if statement. The form of an if statement is as follows:


if (condition) {
    // code goes here
}

For example the following program reads in a number then prints whether it is zero, positive or negative:


import java.util.Scanner;

public class Ifs {

    public static void main(String args[]) {
        int number;

        System.out.print("Enter a number: ");
        Scanner in = new Scanner(System.in);
        number = in.nextInt();

        if (number == 0) {
            System.out.println("The number is zero!");
        }

        if (number > 0) {
            System.out.println("The number is positive!");
        }

        if (number < 0) {
            System.out.println("The number is negative!");
        }
    }
}

 

Boolean Conditions

The portion of an if statement inside parenthesis is called the condition. The condition can either be true or false. This is represented by another Java data type, the bool:

We can declare a variable as a bool, and use the true and false constants:


public class Bools {
    public static void main(String args[]) {
        boolean snowing = true;

        if (snowing) {
            boolean school = false;
        }
    }
}

 

Comparison Operators

As in the positive/negative number check program, we can create boolean values using the following comparison operators:

OperatorMeaning
<Less than.
>Greater than.
<=Less than or equal to.
>=Greater than or equal to.
==Equal to.
!=Not equal to.


 

If / Else Statements

Besides just a plain if statement, we can include an else statement. The form of this is given below:


if (condition) {
    // if portion
} else {
    // else portion
}

Here the program will either do the first block of code, or the second block, depending on whether the condition is true or false.

The following program reads in a users name and age:


import java.util.Scanner;

public class Greet {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        
        System.out.println("Please enter your name and age:");
        String name = in.nextLine();
        int age = in.nextInt();
        
        System.out.println("Hello " + name + " you are " + age + " years old.");
    }
} 

How could we change this so it checks that the age is positive? If so, it prints the message above, otherwise, it gives an error message.





 

Logical Operators

We can also perform calculations on boolean values with logical operators:

OperatorMeaning
&&and
||or
!not

&& is used when we want both things to be true. For example, how can we modify the program above so that it checks that the age is positive and less than 120?




Below is a truth table for &&. It shows that when we && two conditions, it's only true if both are true.

aba && b
falsefalsefalse
falsetruefalse
truefalsefalse
truetruetrue

|| is used when we want to test if at least one of the conditions is true.

Below is a truth table for ||.

aba || b
falsefalsefalse
falsetruetrue
truefalsetrue
truetruetrue

Note that if both conditions are true, combining them with || will result in a true value.

The last logical operator is ! (not) which is simply the opposite of its argument:

a!a
falsetrue
truefalse


 

Example: Ranges

In math, ranges are often expresses as follows:


0 < x < 100

This does not work in Java. How could we write an if statement to test this condition?




How could we write an if statement to test this range condition:


x < 0 or x ≥ 500

Like so:





 

Else / If statements

Sometimes we have more than two different cases we want to test for. This can be done with "else if" statements:


if (condition1) {
    // code for first condition

} else if (condition2) {
    // code for second condition

} else {
    // else portion
}

We can have as many else if statements as we need.

When executing this, the conditions will be checked one by one. Only one section of code will be triggered!


 

Example: Leap Years

The algorithm for determining if a year is a leap year is given below:

  1. If the year is divisible by 400, then it is a leap year.
  2. Else if the year is divisible by 100, then it is not a leap year.
  3. Else if the year is divisible by 4, then it is a leap year.
  4. Else it is not a leap year.

How could we turn this algorithm into a Java program?






 

Blocks & Scope

The curly braces around code in Java are called blocks of code. If the block contains only one statement, the curly braces are not needed. The two if statements are identical:


if (x < y) {
    System.out.println("X is less!");
} else {
    System.out.println("Y is less!");
}

if (x < y)
    System.out.println("X is less!");
else
    System.out.println("Y is less!");

However, it's good practice to always use the curly braces.

Blocks also effect how variables are used in our programs. Every variable has a scope which effects where it can be used.

A variables scope is the block in which it is declared:


public class Scope1 {
    public static void main(String args[]) {
      // x can be used in all of main
      int x = 5;
      System.out.println("x = " + x);

      if (true) {
          // x can be used here too!
          System.out.println("x = " + x);

          // y can be used only in the if block
          int y = 10;
          System.out.println("y = " + y);
      }

      // x can still be used
      System.out.println("x = " + x);

      // but y can't!
      System.out.println("y = " + y);
    }
}

 

Switch Statements

The switch statement is another way to implement multiple selections in Java. It has the form:


switch (variable) {
    case value1:
        // code to run when variable = value1
        break;

    case value2:
        // code to run when variable = value2
        break;

    case value3:
        // code to run when variable = value3
        break;

    default:
        // code to run when none of the previous values were equal to variable
        break;
}

You can have as many different case statements as you like, but they each must be a constant value. The default section is optional. Also, the variable used in the switch must be an integer, char or String type. Double and float values do not work.

The following program that prints the name of a month demonstrates the switch:


import java.util.Scanner;

public class Months {
    public static void main(String args[]) {
        int month, day, year;
        System.out.println("Enter month, day, and year:");
        Scanner in = new Scanner(System.in);
        month = in.nextInt();
        day = in.nextInt();
        year = in.nextInt();

        // print the month by name
        switch (month) {
            case 1:
                System.out.print("January");
                break;
            case 2:
                System.out.print("February");
                break;
            case 3:
                System.out.print("March");
                break;
            case 4:
                System.out.print("April");
                break;
            case 5:
                System.out.print("May");
                break;
            case 6:
                System.out.print("June");
                break;
            case 7:
                System.out.print("July");
                break;
            case 8:
                System.out.print("August");
                break;
            case 9:
                System.out.print("September");
                break;
            case 10:
                System.out.print("October");
                break;
            case 11:
                System.out.print("November");
                break;
            case 12:
                System.out.print("December");
                break;
            default:
                System.out.print("Invalid month!");
                break;        
        }

        System.out.println(" " + day + ", " + year);
    }
}

Note that the break statements are needed to prevent the code "falling through" to the next section. Try removing the breaks and see what happens.


 

Example: Creating Menus

Switch statements are often used for creating menus in programs. For example, if we wanted to make a program to calculate the areas of circles, squares, and triangles, we could make a menu for selecting which shape to use.

How could we write such a program?




Copyright © 2024 Ian Finlayson | Licensed under a Creative Commons BY-NC-SA 4.0 License.