Lecture 9 (Sherriff) - Decisions

Lecture Date: Monday, February 2

Programs that start and then end without any choices to make are boring. If we are going to write a program to do anything interesting, it has to be able to make decisions based on the data it is seeing.

Enter the if statement.

Consider this situation:

ifstatement.png

Pretty straight forward. But how do we make the computer do something different based on the input?

First, how do we decide whether it is cold outside or not?

Well, we could ask the user:

Ask the User
1
2
3
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the temperature outside?: ");
int temp = keyboard.nextInt();

This is good, but this doesn’t yet tell us whether it is specifically cold or not. And that’s different for everyone. So let’s add this:

What is cold?
1
int coldThreshold = 30;

So, now let’s test whether it is cold or not!

Is it cold?
1
2
3
4
5
if(temp <= coldThreshold) {
  wearCoat();
  wearHat();
  wearGloves();
}

There’s another way we could do this - and that’s with what’s called a flag variable. A flag variable is a boolean that we use to determine some sort of state. In this case, we would write it like this:

Is it cold?
1
2
3
4
5
6
7
8
9
10
11
boolean isCold = false;

if(temp <= coldThreshold) {
  isCold = true;
}

if(isCold) {
  wearCoat();
  wearHat();
  wearGloves();
}

This makese the code a bit more readable, and isCold can be easily reused later on.

Now, what if we had to make more of a decision here:

ifelsestatement.png

We could use our flag variable again, but now we will add another option to our if statement:

Is it cold?
1
2
3
4
5
6
7
8
9
10
11
12
boolean isCold = false;

if(temp <= coldThreshold) {
  isCold = true;
}

if(isCold) {
  wearCoat();
}
else {
  wearShorts();
}

In this case, we must do one or the other. A simple if statement either will or will not execute. Here, if the if is not executed, then the else will be.

We can string more of these together as well!

Is it cold?
1
2
3
4
5
6
7
8
9
if(isCold) {
  wearCoat();
}
else if(todayIsSunday) {
  wearBlazer();
}
else {
  wearShorts();
}

Now you are guaranteed to execute one of these three paths.

Other points for today:

  • How to use curly braces
  • Relational operators (<, >, ==, >=, <=, !=)
  • Nested if statements
  • How to test for your letter grade in the class

More code: