Core elements of programs - Control Flow

Introduction

Up to know all your programs have done the same thing over and over. That’s great, but sometimes you want to do different things. You want your program to be able to make decisions.

This section is all about decisions. So firstly…

If Statements

If statements will only run code depending on if a statement evaluates to true. So for example:

int bestestNumber = 8;

if (bestestNumber > 5) {
	//Code inside {} brackets only gets run if bestestNumber is > 5
	System.out.println("BestesetNumbers is greater than 5");
}

The thing that evaluates to true could be a condition (like bestestNumber > 5) OR it could be say a boolean value that is “true”, some function that returns true or even just the word true (or false).

Opeartor list

Operator|What it does|Example :—–:|:—–:|:—–: ==|equal to|(2 == 2) !=|not equal to|(3 != 4) >|Greater than|(5 > 3) >=|Greater than or equal to|(2 >= 2) <|Less than|( 1 < 3) <=|Less than or equal to|(3 <= 3)

When comparing Strings, for silly Java funkiness reasons, you can’t use the == operator. Instead you must use .equals - So:

String bestestVegetable = "potato";
if (bestestVegetable == "potato") {
	//This evaluates to false! Yes it is stupid. yay java.
}
if (bestestVegetable.equals("potato")) {
	//This however will evaluate to be true, and so the following code will run.
	System.out.println("All Hail Lord Potato");
}

And/Or/Not operators

Sometimes you’ll want your code to make a decision based on several evaluations. For that there are “And” and “Or”

E.g.

int value1 = 1;
int value2 = 2;

//And if statment
if((value1 == 1) && (value2 == 2)) {
	System.out.println("value1 is 1 AND value2 is 2");
}

//Or if statement
if((value1 == 1) || (value2 == 1)) {
	System.out.println("value1 is 1 OR value2 is 1");
}

Note that you can chain statements together, and they evaluate using BODMAS bracket rules. So if ( (1==1) && ( (1<=0) || (2==2) ) ) gives true.

If / Else

Sometimes you want to run some code if something is true, and other code if it isn’t. See:

int gabeAlive = false;

if (gabeAlive) {
	System.out.println("Bork");
}
else {
	System.out.println("RIP Gabe")
}

If / Elseif / Else

I can probably show this with an example better than some long explanation. See:

int weAre = 1;
if (weAre == 1) {
	System.out.println("Here's a lesson in Trickery");
}
else if (weAre  <= 10) {
	System.out.println("jk nevermind no lesson 2day");
}
else {
	System.out.println("If you haven't noticed I'm writing this late at night.");
}

So as you can see, it would currently trigger at the first, if, option. BUT if weAre = 8, then it would trigger at the second, else if, option. BUT if it was like 4613, then it would trigger at the last, else, statment

Switch statements

Sometimes you want many many different options and conditions. You can do this with a switch statement! Example time:

int month = 8;
String monthString;
switch (month) {
	case 1:  monthString = "January";
			 break;
	case 2:  monthString = "February";
			 break;
	case 3:  monthString = "March";
			 break;
	case 4:  monthString = "April";
			 break;
	case 5:  monthString = "May";
			 break;
	case 6:  monthString = "June";
			 break;
	case 7:  monthString = "July";
			 break;
	case 8:  monthString = "August";
			 break;
	case 9:  monthString = "September";
			 break;
	case 10: monthString = "October";
			 break;
	case 11: monthString = "November";
			 break;
	case 12: monthString = "December";
			 break;
	default: monthString = "Invalid month";
			 break;
}
System.out.println(monthString);

This would print out “August”.

You can also switch on Strings (and also Enumerations, which are fancy and for later).

String month = "december";
int monthNumber;
switch(month) {
	case "Gabemass": case "Onemass": case "Potatomass"
	case "Ooooh new linemass":
		monthNumber = 42;
	case "december":
		monthNumber = 12;
	default:
		System.out.println("Oh Noes! Invalid Month! The errors... they're coming (dundundun)");
		monthNumber = 0;
}
System.out.println(monthNumber)

Unfortunately, this always returns 0 and prints out the error message. Why? The “break;” was forgotten! The “break;” is really important, without it the program ‘falls through’ and start executing the next cases. So the monthNumber get’s set to 12… but then it keeps on running, prints out the error message, and sets the number to 0. You need to include “break” to remind Java to stop executing the next cases.

As shown above, you can have multiple cases run the same block. “Gabemass”, “Onemass”, “Potatomass” and “Ooooh new linemass” would all get a monthNumber of 42.

everything in a switch statement can be done with ifs. It’s just a judgement call as to what’s more appropiate, makes sense, looks nice, and fits in line with what you’re trying to do.

TODO: Should go in iteration lesson.

Goto / break / continue

There are some… alternative facts ways to jump around in code. These are goto, break and continue. However, they have the tendency to make code messy, unreadable and make spaghettie code (convuloted code with a broken and impossible to understand structure).

Goto actually used to be in Java, but got removed because it’s so bad. Goto lets you jump to specific lines of code. Break will exit a loop. Continue will begin the current loop again.

Not only are goto’s are other horrors bad, but we are legally obligated to warn you that it is a major OSHA healthplace work and safety hazard. XKCD 292 - GOTO

##Activities

  1. Ask someone their favourite colour. Make a judgement as to if they have a chosen a correct favourite colour, and inform them of if they get their decision wrong.
  2. Make a calendar program which will output what the current day of the week is from the date - wikipedia has several methods, see https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#A_tabular_method_to_calculate_the_day_of_the_week . Note that a (whole) number % 100 will return the last two digits (10s and 0s). (FYI you can have people enter in the date seperately - i.e. ask the day, month and year.)