Building Java Programs

Lab 4: Ch. 4: If/Else, Scanner, Cumulative Algorithms

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

lab document created by Marty Stepp and Stuart Reges

Today's lab

Goals for today:

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 : if/else mystery practice-it

Consider the following Java code.

public static void ifElseMystery(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.

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

if/else factoring

Exercise : if/else Factoring

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.

Exercise : AgeCheck

Exercise - things to fix

Exercise - answer

Exercise : AgeCheck2

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:

User input and Scanner

Method name Description
nextInt() reads and returns the next token as an int, if possible
nextDouble() reads and returns the next token as double, if possible
next() reads and returns a single word as a String
nextLine() reads and returns an entire line as a String

Example:

import java.util.*;   // so you can use Scanner
...
Scanner console = new Scanner(System.in);
System.out.print("How old are you? ");   // prompt
int age = console.nextInt();
System.out.println("You typed " + age);

Exercise : DevryAdmit practice-it

Write a complete program DevryAdmit with the behavior shown below. Use the Scanner to read user input for a student's grade point average and SAT exam score. A GPA below 1.8 will cause the student to be rejected; an SAT score below 900 will also cause a rejection. Otherwise the student is accepted.

Devry University admission program
What is your GPA? 3.2
What is your SAT score? 1280
You were accepted!

Check your answer using Practice-It from the check-mark icon above.

Exercise : ProcessName practice-it

Copy/paste and save icon ProcessName.java in jGRASP, then go to the next slide.

import java.util.*;  // for Scanner

public class ProcessName {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        System.out.print("Type your name: ");
        
        // your code goes here
        
        System.out.println("Your name is: " + name);
    }
}

continued on the next slide ...

Exercise - code to add practice-it

Exercise : Syntax errors

Exercise - answer

  1. line 5: nextString should be next
  2. line 9: string should be String
  3. line 9: name should not be in quotes
  4. line 10: Whitaker should be in quotes
  5. line 10: cannot compare strings with ==; must use .equals
  6. line 13: cannot call replace without specifying a string object (name)
  7. line 14: toUppercase should be toUpperCase
  8. line 14: name. should come before toUpperCase, not passed as a parameter to it
  9. line 14: must say name = to store the result of toUpperCase
  10. line 15: must say name = to store the result of substring
  11. line 16: must use parentheses () when calling length

Exercise - Corrected version

public class StringOops {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        System.out.print("Type your name: ");
        String name = console.next();
        process(name);
    }

    public static void process(String "name") {
        if (name.equals("Whitaker")) {
            System.out.println("You must be really awesome.");
        }
        name = name.replace("a", "e");
        name = name.toUpperCase();
        name = name.substring(0, 3);
        System.out.println(name + " has " + name.length() + " letters");
    }
}

Cumulative algorithms

Exercise : repl practice-it

Exercise : longestName practice-it

Write a method named longestName that reads names typed by the user and prints the longest name (the name that contains the most characters) in the format shown below. Your method should accept a console Scanner and an integer n as parameters and should then prompt for n names.

A sample execution of the call longestName(console, 4) might look like the following:

name #1? roy
name #2? DANE
name #3? sTeFaNiE
name #4? Erik
Stefanie's name is longest

Try to solve this problem in Practice-It: click on the check-mark above!

Exercise : swapPairs practice-it

Exercise : jGRASP Debugger

We are going to practice using the jGRASP debugger with Hailstone.java. This program computes a sequence of integers called a hailstone sequence. (This is related to an unsolved problem in mathematics known as the Collatz Conjecture.)

continued on the next slide...

Exercise - Values of value

# value
first value 7
second value 22
third value
11
fourth value
34
fifth value
17
sixth value
52

continued on the next slide...

Exercise - Values of min

# min
first value 7
second value
5
third value
4
fourth value
2
fifth value
1

Exercise : hopscotch practice-it

Write a method named hopscotch that accepts an integer parameter for a number of "hops" and prints a hopscotch board of that many hops.

For example, the call hopscotch(3); would produce the following output:

   1
2     3
   4
5     6
   7
8     9
   10

Try to solve this problem in Practice-It: click on the check-mark above!

If you finish them all...

If you finish all the exercises, try out our Practice-It web tool. It lets you solve Java problems from our Building Java Programs textbook.

You can view an exercise, type a solution, and submit it to see if you have solved it correctly.

Choose some problems from the book and try to solve them!