University of Washington, AP/CS A

Lab 4: if else

Except where otherwise noted, the contents of this document are Copyright 2013 Stuart Reges and Marty Stepp.

lab document created by Marty Stepp, Stuart Reges and Whitaker Brand

Today's lab

Goals for this lab:

Conditional Statements

Conditional statements lets your program choose to do different things based on the results of tests, which evaluate certain parts of a program. There are 3 structures that we can use:

if statements

if statements are composed of a test, and some code to execute if that test is true (ex. 2 + 2 = 4 is true).

if (test) {
    statement(s);  // executes if test is true
} 
System.out.println("yay!")  // prints yay, business as usual outside the if  statement

Example:

if (gpa >= 2.0) { 
    System.out.println("Welcome to Mars University!");  // perform this code is gpa >= 2.0
}

Exercise : if statements

What does the following code output?
1
2
3
4
5
x = 5;
if (x < 0) {
    System.out.println("inside if branch!");
} 
System.out.println("outside if branch!");

Output:

outside if branch!

Exercise : if statements

What does the following code execute?
1
2
3
4
5
x = -2;
if (x < 0) {
    System.out.println("inside if branch!");
} 
System.out.println("outside if branch!");

Output:

inside if branch!
outside if branch!

Exercise : if statements

What does the following code execute?
1
2
3
4
5
6
7
8
x = -2;
if (x < 0) {
    System.out.println("inside if branch!");
} 
if (x < -1) {
    System.out.println("inside this branch!");
}
System.out.println("outside if branch!");

Output:

inside if branch!
inside this branch!
outside if branch!

Note: it's possible for any if statement to execute, or not. If you have a couple if statements next to each other, 0 of them, 1 of them, or both of them could execute.

if/else statements

if/else statements are statements that include two branches, one of which is always executed. They allow us to control our program's behavior when the if statement's test evaluates to false.

if (test) {
    statement
} else {              //  implicitly, test is false
    statement
}

Example:

if (gpa >= 2.0) {
    System.out.println("Welcome to Mars University!");  // perform this code is gpa >= 2.0
} else { 
    System.out.println("Please apply again soon.");     // perform this code is gpa < 2.0
}

Exercise : if-else practice

What does the following program output?
1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
   int x = 5;
   if (x < 5) {
      System.out.println("abc");
   } else {
      System.out.println("def");
   }
   System.out.println("ghi");
}

Output:

def
ghi

Exercise : if-else practice

What does the following program output?
1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
   int x = 2;
   if (x < 5) {
      System.out.println("abc");
   } else {
      System.out.println("def");
   }
   System.out.println("ghi");
}

Output:

abc
ghi

Note: With if-else structures, exactly one branch will execute. It is impossible for neither the if branch or the else branch to execute. It is also impossible for both to execute.

nested if/else statements

Nested if/else statements allow you to write code that executes if its test is met, but only in the case that an if statement before it has already evaluated to false.

if (test1) {
   statement  // executes if test1 == true
} else if (test2) {
   statement  // executes if test1 -= false AND test 2 == true
}
Example:
if (gpa >= 2.0) { 
    System.out.println("Welcome to Mars University!");  // perform this code is gpa >= 2.0
} else if (gpa < 0.7) 
    System.out.println(":*(");  // perform this code when gpa < 2.0 and < 0.7 
}

Exercise : if/else mystery

public static void mystery(int n) {
    System.out.print(n + " ");
    if (n > 10) {
        n = n / 2;
    } else {
        n = n + 7;
    }
    if (n * 2 < 25) {
        n = n + 10;
    }
    System.out.println(n);
}
Fill in the boxes with the output produced by each of the method calls.
mystery(40);
40 20
mystery(0);
0 17
mystery(12);
12 16
mystery(20);
20 20

Exercise : if/else mystery

public static void mystery2(int a, int b) {
    if (a < b) {
        a = a * 2;
    }
    if (a > b) {
        a = a - 10;
    } else {
        b++;
    }
    System.out.println(a + " " + b);
}

Fill in the boxes with the output produced by each of the method calls.

mystery2(10, 3);
0 3
mystery2(6, 6);
6 7
mystery2(3, 4);
-4 4
mystery2(4, 20);
8 21

Exercise : if/else mystery

public static void mystery3(int x, int y) {
    int z = 4;
    if (z <= x) {
        z = x + 1;
    } else {
        z = z + 9;
    }
    if (z <= y) {
        y++;
    }
    System.out.println(z + " " + y);
}
Fill in the boxes with the output produced by each of the method calls.
mystery3(3, 20);
13 21
mystery3(4, 5);
5 6
mystery3(5, 5);
6 5
mystery3(6, 10);
7 11

Exercise : Syntax errors

Exercise - answer

  1. line 5: if statement should use () parentheses, not {} brackets
  2. line 5: = should be ==
  3. line 5: smaller is out of scope here
  4. line 10: void should be int
  5. line 13: => should be >= (or better yet, no if test is needed)
  6. line 16: should not write variable's type of int when returning it
  7. line 16: int smaller is out of scope here (declare outside if or return directly)

Exercise - Corrected version

Exercise : seeMovie practice-it

You're thinking about going with your friends to a movie. Write a Java method seeMovie that accepts two parameters: the cost of a ticket in dollars, and the rating number of stars the movie received out of 5. The method should print how interested you are (very, sort-of, or not). Use the following criteria:

Exercise : AgeCheck

Exercise - things to fix

Exercise - answer

Exercise : numUnique practice-it

Write a method named numUnique that accepts three integers as parameters and that returns the number of unique integers among the three. For example, the call numUnique(18, 3, 4) should return 3 because the parameters have 3 different values. By contrast, the call numUnique(6, 7, 6) would return 2 because there are only 2 unique numbers among the three parameters: 6 and 7.

Compare your solution to your neighbors'. Did you all solve it the same way?

Exercise : pay practice-it

Write a method named pay that accepts two parameters: a real number for a TA's salary, and an integer for the number of hours the TA worked this week. The method should return how much money to pay the TA. For example, the call pay(5.50, 6) should return 33.0.

The TA should receive "overtime" pay of 1 ½ normal salary for any hours above 8. For example, the call pay(4.00, 11) should return (4.00 * 8) + (6.00 * 3) or 50.0.

if/else factoring

Recall that with if/else, exactly 1 branch executes. This make a new kind of redundancy possible!
if (x < 30) {
    a = 2;
    x++;
    System.out.println("CSE 142 TAs are awesome! " + x);
} else {
    a = 2;
    x--;
    System.out.println("CSE 142 TAs are awesome! " + x);
}
Because the red code will happen no matter what (in the if and the else case), it can be factored out:
a = 2;
if (x < 30) {
    x++;
} else {
    x--;
}
System.out.println("CSE 142 TAs are awesome! " + x);

Exercise : if/else Factoring

Exercise : if/else Factoring

Expected Output
I'm valedictorian for this class! Woo hoo!
I made the dean's list for this class!
I received 5 credits for this class.

I made the dean's list for this class!
I received 5 credits for this class.

I received 5 credits for this class.

Uh-oh..I probably should have studied a little more.
I received 0 credits for this class.

Uh-oh..I probably should have studied a little more.
I received 5 credits for this class.

Exercise : if/else Factoring

    public static void factoring(double gpa) {
        int credits = 5;  // since we want credits = 5 in all cases except gpa <= 0.7
        if (gpa == 4.0) {
	    credits = 5;
            System.out.println("I'm valedictorian for this class! Woo hoo!");
            System.out.println("I made the dean's list for this class!");  
	}
        else if (gpa >= 3.5) {  // we want the same behavior for all gpa >= 3.5 cases (4.0 or not) 
            credits = 5;
            System.out.println("I made the dean's list for this class!");
        } else {
            credits = 5;
        } else if (gpa < 1.5) {  // gpa can be < 1.5, >= 3.5, or neither
            System.out.println("Uh-oh..I probably should have studied a little more.");
        }
        if (gpa <= 0.7) {
            System.out.println("Uh-oh..I probably should have studied a little more.");
            credits = 0;
        }
        System.out.println("I received " + credits + " credits for this class.");
        System.out.println();
    }

Exercise : season practice-it

Exercise : before practice-it

Write a method before that takes as parameters two month/day combinations and that returns whether or not the first date comes before the second date (true if the first month/day comes before the second month/day, false if it does not). The method will take four integers as parameters that represent the two month/day combinations.

The first integer in each pair represents the month and will be a value between 1 and 12 (1 for January, 2 for February, etc, up to 12 for December). The second integer in each pair represents the day of the month (a value between 1 and 31). One date is considered to come before another if it comes earlier in the year.

Solve this problem in Practice-It by clicking on the check-mark above.