Building Java Programs

Lab: if/else

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

Lab goals

Goals for this problem set:

if/else Statements

An if/else statement lets your program choose between 2 or more options.

if (test) {
    statement(s);
} else {
    statement(s);
}

Example:

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

Exercise : if/else mystery

Consider the following Java code. Fill in the boxes with the output produced by each of the method calls.

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);
}
mystery(40);
40 20
mystery(8);
8 15
mystery(0);
0 17
mystery(12);
12 16
mystery(20);
20 20

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 : quadrant practice-it

Write a method quadrant that accepts a pair of real numbers x and y and returns the quadrant for that point:

For example, quadrant(-2.3, 14.2) returns 2. If the point falls directly on either axis, return 0.

if/else factoring

Exercise : if/else Factoring

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 : AgeCheck

Exercise - things to fix

Exercise - answer

Exercise : AgeCheck2

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: