Object Oriented Programming

Week 2: Conditional statements and loops

Introduction

This week we will look at conditional statements (if statements) and loops (while, do/while and for loops). You have already seen examples of each in Python but this Topic will show you how to write them in Java.

The if statement in Java

This example shows how to do an if statement in Java:

import java.util.Scanner;

public class GuessTheYearApp
{
    public static void main (String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println ("Which year was the most recent London Olympics?");
        String yearAsString = scanner.nextLine();
        int year = Integer.parseInt(yearAsString);
        
        if(year==2012)
        {
            System.out.println("Correct!");
        }
        else
        {
            System.out.println("Wrong!");
        }
    }
}
Hopefully you can recognise the if / else structure that you have seen already in Python. The main things to note here are:

In addition to simply having an if block and an else block, we can also have one or more else if blocks to handle multiple conditions. The example below shows this (the previous London Olympics before 2012 was in 1948):

import java.util.Scanner;

public class GuessTheYearApp2
{
    public static void main (String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println ("Which year was the most recent London Olympics?");
        String yearAsString = scanner.nextLine();
        int year = Integer.parseInt(yearAsString);
        
        if(year==2012)
        {
            System.out.println("Correct!");
        }
        else if (year==1948)
        {
            System.out.println("I said the *most recent* London Olympics!");
        }
        else
        {
            System.out.println("Wrong!");
        }
    }
}

Comparison and logical operators in Java

Like other languages, Java has comparison and logical operators. Here is a list of the most common comparison operators:

and here are the two most common logical operators:

Exercise 1

  1. Modify the second example above so that the "I said the most recent..." message appears if the user entered 1908 as well as 1948. (There was also a London Olympics in 1908).
  2. Modify the second example above so that it displays "Earlier!" if the year was after 2012 or "Later!" if the year was before 2012.
  3. Write a program to calculate a train fare dependent on your age. Imagine that train fares are half price if you are under 18 or over 65. The program should allow the user to enter the full-price train fare (a double) and the user's age, and then display the train fare that the user has to pay dependent on their age. There is a Double.parseDouble() which is equivalent to Integer.parseInt() for converting Strings to doubles.
  4. Enhance this program so that invalid ages (an age less than 0, or an age of 128 or more) are rejected. The program should just end (you can use System.exit(0); to quit the program)

Loops in Java

In common with other languages, you can write loops in Java. You should remember from Introduction to Programming and Problem Solving that a loop involves repeating the same section of code over and over again until some condition is met. Java has four types of loops:

We will look at the first three for now, and come back to the foreach loop later.

The "while" loop in Java

The while loop is probably the simplest loop in Java. It simply loops until a particular condition is met. For example:

public class WhileLoopApp
{
    public static void main (String[] args)
    {
        int i = 1;
        
        while(i <= 10)
        {
            System.out.println("Number = " + i);
            System.out.println("Square of number = " + i*i);
            i++;
        }
    }
}
This example initialises an integer variable i to 1 and then loops while the variable i is less than or equal to 10. Of note is:

Exercise 2

  1. Change the program above to count down from 20 to 2 in steps of 2.
  2. Rewrite the basic "Guess the Olympics year" program to use a while loop rather than an if statement, so that if the user gets the year wrong, they should be given another chance. (This should be the basic version of the program, do not worry about previous Olympic years; just say "Correct" or "Wrong" depending on whether it's 2012 or not. Also, initially, do not distinguish between pre-2012 and post-2012 years).
  3. Enhance question 2 so that the program distinguishes between pre-2012 and post-2012 years, by having an if statement inside your while loop.

The "do/while" loop in Java

The do/while loop is similar to the while loop, but performs the check at the end of the loop rather than the beginning. For example:

public class DoWhileLoopApp
{
    public static void main (String[] args)
    {
        int i = 1;
        
        do
        {
            System.out.println("Number = " + i);
            System.out.println("Square of number = " + i*i);
            i++;
        }while(i <= 10);
    }
}
Sometimes the logic of a loop means that it's better to put the check at the end of the loop rather than the beginning, and the do/while loop allows us to do that. Note also how we need to put a semicolon after the while condition; this is because the statement ends here, whereas for a while loop the condition is at the beginning of the loop. A common mistake is to add a semicolon to an ordinary while loop:
public class InfiniteWhileLoopApp
{
    public static void main (String[] args)
    {
        int i = 1;
        
        while(i <= 10);
        {
            System.out.println("Number = " + i);
            System.out.println("Square of number = " + i*i);
            i++;
        }
    }
}
This is a logical error because a semicolon always terminates a statement, and in this example will therefore terminate the while statement and separate it from its code block. while(i <= 10); is basically equivalent to writing the while loop with an empty code block, i.e.:
while(i <= 10)
{
}
The result is that the while statement will loop infinitely, because it is testing for i being less than or equal to 10, and i is never increased beyond 1 within the loop.

The for loop

Java also has a for loop, in common with many other languages. The for loop might take some getting used to if you have not programmed in any other "C like" language such as C or C++. The syntax is:

for(initialisation; continue condition; change)
where: An example:
for(int i=1; i<=10; i++)
Here: Here is a full example:
public class ForLoopApp
{
    public static void main (String[] args)
    {    
        for(int i=1; i <= 10; i++)
        {
            System.out.println("Number = " + i);
            System.out.println("Square of number = " + i*i);
        }
    }
}
Compare this to the while loop example. While it may be a little harder to understand the syntax of the for loop if you are new to it, it is more concise. When we used a while loop, we needed to initialise i and increase i by one on separate lines; with a for loop, we put both those lines inside the for statement.

Exercise 3

  1. Using a for loop, write a program to display a given character a certain number of times. Ask the user for the character and the number of times from the keyboard. For example if they entered "#" and 8, it should display:
    ########
    Hint: Use System.out.print(), rather than System.out.println(), to display a string without starting a new line.
  2. Using a for loop within another for loop, write a program to display an ASCII-art triangle with a certain number of lines. Each line should have one character more than the previous. The user should be able to enter the character (as a string) and the number of lines. For example if the user entered "*" and 4, it should display:
    *
    **
    ***
    ****
    Hint: Use System.out.print("\n"); to start a new line. \n is one of several escape codes in Java: it is a special code to indicate a new line.

Additional Material: The switch statement

If you finish this topic early, look at this additional material on the switch statement.