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.
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:
if(year==2012)Note how we use == (double equals) to test whether a variable is equal to a value. A single equals (=) is used to assign a value to a variable.
System.out.println("Correct!");will run if the user entered the correct year, while the statement:
System.out.println("Wrong!");will run if the user entered the wrong year.
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!"); } } }
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:
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:
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:
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.
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:
for(int i=1; i<=10; i++)Here:
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.
########Hint: Use System.out.print(), rather than System.out.println(), to display a string without starting a new line.
* ** *** ****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.
If you finish this topic early, look at this additional material on the switch statement.