University of Washington, CSE 142

Lab 3: Return, if/else, and Scanner

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

lab document created by Marty Stepp, Stuart Reges, Whitaker Brand and Hélène Martin

Basic lab instructions

Today's lab

Goals for today:

Exercise : Check MyUW scores

class mean for a1 (i.e., average score for assignment 1) / 10
9.19
class mean for lab1 (i.e., average score for lab 1) / 2
1.95

Returning Values

A return value is when a method sends a value back to the code that called it.

public static type name(parameters) {      // declare
    ...
    return expression;
}
variableName = methodName(parameters);     // call

Example:

public static double fToC(double tempF) {
    return (tempF - 32) * 5.0 / 9.0;
}
...
double bodyTemp = fToC(98.6);          // bodyTemp stores 37.0
double freezing = fToC(32);            // freezing stores  0.0

Math expression syntax

Method Description Example
Math.abs absolute value Math.abs(-308) returns 308
Math.ceil ceiling (rounds upward) Math.ceil(2.13) returns 3.0
Math.floor floor (rounds downward) Math.floor(2.93) returns 2.0
Math.max max of two values Math.max(45, 207) returns 207
Math.min min of two values Math.min(3.8, 2.75) returns 2.75
Math.pow power Math.pow(3, 4) returns 81.0
Math.round round to nearest integer Math.round(2.718) returns 3
Math.sqrt square root Math.sqrt(81) returns 9.0

Exercise - Math expressions

Write the results of each expression. Use the proper type (such as .0 for a double). Note that a variable's value changes only if you re-assign it using the = operator. Discuss any errors you make with your neighbor.

double grade = 2.7;
Math.round(grade);                               // grade = 2.7
grade = Math.round(grade);                       // grade = 3.0

double min = Math.min(grade, Math.floor(2.9));   //   min = 2.0

double x = Math.pow(2, 4);                       //     x = 16.0
x = Math.sqrt(64);                               //     x = 8.0

int count = 25;
Math.sqrt(count);                                // count = 25
count = (int) Math.sqrt(count);                  // count = 5

int a = Math.abs(Math.min(-1, -3));              //     a = 3

Exercise : area practice-it

Consider the following method for converting milliseconds into days:

// converts milliseconds to days
public static double toDays(double millis) {
    return millis / 1000.0 / 60.0 / 60.0 / 24.0;
}

Write a similar method named area that takes as a parameter the radius of a circle and that returns the area of the circle. For example, the call area(2.0) should return 12.566370614359172. Recall that area can be computed as π times the radius squared and that Java has a constant called Math.PI.

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 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.

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.

Cumulative algorithms

Exercise : Scanner sum

Copy and paste the following code into jGrasp.

public class SumNumbers {
    public static void main(String[] args) {
        int low = 1;
        int high = 1000;
        int sum = 0;
        for (int i = low; i <= high; i++) {
            sum += i;
        }
        System.out.println("sum = " + sum);
    }
}

continued on next slide...

Exercise : Scanner sum

Modify the code to use a Scanner to prompt the user for the values of low and high. Below is a sample execution in which the user asks for the same values as in the original program (1 through 1000):

low? 1
high? 1000
sum = 500500

Below is an execution with different values for low and high:

low? 300
high? 5297
sum = 13986903

You should exactly reproduce this format.

Use the Output Comparison Tool to check your work.

Exercise : pow practice-it

Write a method named pow that accepts a base and an exponent as parameters and returns the base raised to the given power. For example, the call pow(3, 4) returns 3 * 3 * 3 * 3 or 81. Do not use Math.pow in your solution; use a cumulative algorithm instead. Assume that the base and exponent are non-negative. See ch4 lecture slides on cumulative sums for a hint.

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:

Exercise : Spiral practice-it

spiral

Write a Java program that draws the following output using a for loop.

Exercise - answer

import java.awt.*;

public class Spiral {
    public static void main(String[] args) {
        DrawingPanel panel = new DrawingPanel(170, 170);
        Graphics g = panel.getGraphics();
        for (int i = 0; i < 8; i++) {
            g.drawLine(      10*i,   10 + 10*i, 160 - 10*i,  10 + 10*i);  // top
            g.drawLine(160 - 10*i,   10 + 10*i, 160 - 10*i, 160 - 10*i);  // right
            g.drawLine( 10 + 10*i,  160 - 10*i, 160 - 10*i, 160 - 10*i);  // bottom
            g.drawLine( 10 + 10*i,   20 + 10*i,  10 + 10*i, 160 - 10*i);  // left
        }
    }
}

Exercise - answer, alternative version

import java.awt.*;

public class Spiral {
    public static void main(String[] args) {
        DrawingPanel panel = new DrawingPanel(170, 170);
        Graphics g = panel.getGraphics();
        int x = 0, y = 10;
        int len = 160;
        for (int i = 0; i < 8; i++) {
            g.drawLine(x, y, x + len, y);  // right
            x = x + len;
            len = len - 10;
            g.drawLine(x, y, x, y + len);  // down
            y = y + len;
            g.drawLine(x, y, x - len, y);  // left
            x = x - len;
            len = len - 10;
            g.drawLine(x, y, x, y - len);  // up
            y = y - len;
        }
    }
}

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!