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
Goals for this lab:
if
, else if
, and else
to have
different branches of executionConditional
StatementsConditional 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
else
statements
else if
statements
if
statementsif
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
}
if
statements
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! |
if
statements
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! |
if
statements
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
statementsif/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 }
if-else
practice
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 |
if-else
practice
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.
if/else
statementsNested 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 }
if
/else
mysterypublic 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 |
if
/else
mysterypublic 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 |
if
/else
mysterypublic 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 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class IfOops { public static void main(String[] args) { int a = 7, b = 42; minimum(a, b); if {smaller = a} { System.out.println("a is the smallest!"); } } public static void minimum(int a, int b) { // returns which int is smaller if (a < b) { int smaller = a; } else (a => b) { int smaller = b; } return int smaller; } } |
if
statement should use ()
parentheses, not {}
brackets=
should be ==
smaller
is out of scope herevoid
should be int
=>
should be >=
(or better
yet, no if
test is needed)int
when
returning itint smaller
is out of scope here (declare
outside if
or return directly)public class IfOops { public static void main(String[] args) { int a = 7, b = 42; int smaller = minimum(a, b); if (smaller == a) { System.out.println("a is the smallest!"); } } public staticvoidint minimum(int a, int b) { // returns which int is smaller int smaller; if (a < b) {intsmaller = a; } elseif (a >= b){intsmaller = b; } returnintsmaller; } }
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:
public class AgeCheck { public static void main(String[] args) { int myAge = 19; // I am 19; let me see if I can drive message(myAge); } // Displays message about driving to user based on given age public static void message(int age) { if (myAge >= 16) { System.out.println("I'm old enough to drive!"); } if (myAge <= 16) { System.out.println("Not old enough yet... :*("); } } }
if
and else
in a clumsy way.
Improve the style of the code.
public class AgeCheck { public static void main(String[] args) { int myAge = 19; // I am 19; let me see if I can drive message(myAge); } // Displays a message about driving to user based on given age public static void message(int age) { if (age >= 16) { System.out.println("I'm old enough to drive!"); } else { System.out.println("Not old enough yet... :*("); } } }
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?
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
factoringif/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);
if
/else
Factoringif
to an else if
).
if/else
FactoringI'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.
if/else
Factoringpublic 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!");}elseif (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(); }
season
that takes two integers as
parameters representing a month and day and that returns a String
indicating the season for that month and day. Assume that months are
specified as an integer between 1 and 12 (1 for January, 2 for February,
and so on) and that the day of the month is a number between 1 and 31.
"Winter"
. If the date falls between 3/16 and 6/15,
you should return "Spring"
. If the date falls between 6/16
and 9/15, you should return "Summer"
. And if the date falls
between 9/16 and 12/15, you should return "Fall"
.
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.