Saturday, 13 August 2016

Java Tutorial 7 - Conditional Statements

Last Time
We looked at arrays, what they are and how to use them

This tutorial
We will be looking at conditional statements

What are conditional statements and how are they useful
So far, all the programs we have written have been sequential, first line 1 was run, then line 2, then line 3 etc. Most of the time, you'll want your program to run different commands based on some condition. For example, if you were making a game, you'd want to do something if the user clicked, but something different if they user didn't click. This is where conditional statements come in. We can check a statement, and if it is true, do one thing, otherwise, do another thing

Writing conditional statement
A conditional statement is formatted like so:
    //to do if condition is true

int age = 15;
if(age < 18){
    System.out.println("You are not an adult");

This simple code will simply print "You are not an adult" if the value of the age variable is under 18. We used the < sign to check this, here are some more you can use

> More than
< Less than
== equal to (note this is 2 = signs)
>= more than or equal to
<= less than or equal to
!= not equal to

If else
Sometimes we want to run code when a condition is not met. In these cases we can use an else clause such as:

int age = 15;
if(age < 18){
    System.out.println("You are not an adult");
    System.out,println("you are an adult");

This code runs a different command depending on the value of age. Try running this yourself then try changing age to 21. Notice the difference in the output.

Else if
We can also check multiple conditions to see if they are true, for example in a menu

int option = 3;
if(option == 1){
    System.out.println("Option 1 has been chosen");
else if(option == 2){
    System.out.println("Option 2 has been chosen");
else if(option == 3){
    System.out.println("Option 3 has been chosen");
else if(option == 4){
    System.out.println("Option 4 has been chosen");

This code checks for each of these values and prints a statement accordingly

Next lesson, we will look at user input and build a program the user can interact with

No comments:

Post a Comment