common/conf common/conf CSE 142 Lab 4: Return, if/else, and Scanner

University of Washington, CSE 142

Lab 4: Return, if/else, and Scanner

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

Basic lab instructions

Today's lab

Goals for today:

Returning Values

A return value is information that a method gives back to the code that called it. Every method can only return one value: when a method returns, it stops executing (and we resume where we left off before the method was called). For the code that called the method to use the returned value, the returned value must be stored in a variable or used immediately.

public static type methodName(parameters) {      // calling methodName returns expression
    ...
    return expression;
}
type variableName = methodName(parameters);     // variableName stores return value

Exercise : Returns

What does the following output?
1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
    int x = 5;
    x = mystery();
    System.out.println(x);
}

public static int mystery() {
    return 8;
}

Output:

8

Exercise : Returns

What does the following output?
1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
    int x = 5;
    mystery();
    System.out.println(x);
}

public static int mystery() {
    return 8;
}

Output:

5

Exercise : Dating made easy!

They say that it's okay to date someone who is at least 1/2 your age + 7 years old. Write a class called DatingCalculator, and copy the following code into it.

    public static void main(String[] args) {
        double x = ageCalculator(19); 
        double y = ageCalculator(32);
        double z = ageCalculator(99);
        
        System.out.println(x); // prints 16.5
        System.out.println(y); // prints 23.0
        System.out.println(z); // prints 56.5
    }

Then write the method called ageCalculator, which takes an age as an int and returns the youngest age that someone of that age should date, as a double. For example, you should get the following output:

16.5
23.0
56.5
Hint: if you're getting 16.0 and 56.0 instead of 16.5 and 56.5, think back to lab 2. What's the difference between int and double division?

Exercise : Solution

Here is one possible solution:

public class DatingCalculator {
    public static void main(String[] args) {
        double x = ageCalculator(19); 
        double y = ageCalculator(32);
        double z = ageCalculator(99);
        
        System.out.println(x); // prints 16.5
        System.out.println(y); // prints 23.0
        System.out.println(z); // prints 56.5
    }
    
    public static double ageCalculator(int input) {
        return input / 2.0 + 7;
    }
}

Math expression syntax

Method Return 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

Fill in the value of the variable asked about in the comment. 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. You can put an expression into the Interactions pane if you're stuck! (Remember to leave off the ; s in Interactions!)

int min = Math.min(2, 5);                  //   min   = 2
int max = Math.max(4, 9);                  //   max   = 9

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

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

int abs = Math.abs(-8);                    //   abs   = 8

Exercise - Math expressions

Fill in the value of the variable asked about in the comment. 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. You put an expression in the Interactions pane if you're stuck! (Remember to leave off the ; s in Interactions!)

long rounded = Math.round(2.9);                //   rounded     =   3
rounded = Math.round(6.4);                     //   rounded     =   6

double grade = 2.7;                            //    grade      =   2.7
Math.round(grade);                             //    grade      =   2.7
long roundedGrade = Math.round(grade);         // roundedGrade  =   3
roundedGrade = Math.max(roundedGrade, 4);      // roundedGrade  =   4

double floor = Math.floor(2.9);                //    floor      =   2.0

double ceiling = Math.ceil(8.4);               //     ceil      =   9.0

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.

Scanners

A Scanner is an object that reads input. It parses the incoming text, and lets us access it word by word, or line by line.

    Scanner scannerName = new Scanner(inputToRead);

What kind of input can Scanners read over? Files, network connections, tons of things!

We're going to start by reading input from the user. This is how to create a Scanner that can ask the user for input, which comes in through System.in:

    // console is a common name for a user-input Scanner
    Scanner console = new Scanner(System.in);

User input and Scanner

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

import java.util.*;                       // so you can use Scanner
          
          ...

Scanner console = new Scanner(System.in); // "System.in" = scanner reads from the console
System.out.print("How old are you? ");    // prompt
int age = console.nextInt();              // reads from the console
System.out.println("You typed " + age);

Scanner method examples

Suppose we have a Scanner trying to read over the following:
    4.2 abc 4
The following methods would read this as:
Method What happened? What's going on?
nextInt() java.util.InputMismatchException tried to read next token 4.2, couldn't process it as an int.
nextDouble() returns 4.2 as a double. tried to read next token, succeeded because it could be read as a double.
next() returned "4.2" as a String. read the next word as a String.
nextLine() returns "4.2 abc 4" as a String. read the whole next line as a String.

⚠ CAUTION: do not mix .next() and .nextLine()! ⚠

Mixing .next() and .nextLine() will give unexpected results. Make sure that each Scanner you create only reads words (using .next()) OR entire lines (.nextLine())!

Exercise : Working with Scanners!

Copy and paste the following code into jGrasp.

import java.util.*;  // needed to use Scanners

public class Introduction {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      System.out.print("What's your age? ");     // prompt, note the print() (not a println())
      int age = input.nextInt(); 
      System.out.println("You are " + age);
   }
} 

Try running the program and entering in your age (or any number). What happens if you enter something that isn't an integer? What happens if you enter a random word like "banana"?

continued on next slide...

Exercise : Working with Scanners

Now modify the code so that it prompts the user to enter their name, stores the user's String input in a String variable, then prints the user's name rather than their age.

Example output:
What's your name? Brett
You are Brett

The solution is on the next slide, if you get stuck!

Exercise : Solution

This is one possible solution:

import java.util.*; // needed to use Scanners

public class Introduction {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      System.out.print("What's your name? ");
      String name = input.next();
      System.out.println("You are " + name);
   }
}
Can you still enter an integer in this modified program? What about a double? Why?

Cumulative algorithms

A cumulative algorithm involves incrementally accumulating a value by repeatedly adding, multiplying, dividing, etc., while storing the result in a variable.

Key aspects of a cumulative algorithm: A loop, and a variable declared outside the loop whose value is modified inside the loop.

Example: Cumulative algorithm to sum the numbers 1-100:
int sum = 0;                // safe default value, 0 doesn't affect a sum
for (int i = 1; i <= 100; i++) {
    sum = sum + i;
}
System.out.println(sum);    // 5050

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.

Exercise : Scanner sum solution

import java.util.*;

public class SumNumbers {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        
        System.out.print("low? ");
        int low = console.nextInt();
        System.out.print("high? ");
        int high = console.nextInt();
        
        int sum = 0;
        for (int i = low; i <= high; i++) {
            sum += i;
        }
        System.out.println("sum = " + sum);
    }
}

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
  • else statements
  • else if statements

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

What does the following code output?


      
public static void main(String[] args) {
   int x = 5;
   if (x > 6) { 
      System.out.println("abc");
   } else if (x < 6) {
      System.out.println("def");
   }
   System.out.println("ghi");
}

Output:

def
ghi

Exercise : else-if practice

What does the following code output?


      
public static void main(String[] args) {
   int x = 4;
   if (x < 5) { 
      System.out.println("abc");
   } else if (x < 6) {
      System.out.println("def");
   }
   System.out.println("ghi");
}

Output:

abc
ghi

Exercise : else-if practice

What does the following code output?


      
public static void main(String[] args) {
   int x = 8;
   if (x < 5) { 
      System.out.println("abc");
   } else if (x < 6) {
      System.out.println("def");
   }
   System.out.println("ghi");
}

Output:

ghi

Note that even if both the if and else if tests are satisfied, we still only execute 1 of the branches at most! It's also possible for neither the if or else if branches to execute.

Exercise : if/else mystery

public static void mystery0(int a, int b) {
    int c = 5;
    if (a < b) {
        c = 6;
    } 
    if (b < 8) {
        a = 10;
    } else {
        b = 8;
    }
    System.out.println(a + " " + b + " "  + c);
}
Fill in the boxes with the output produced by each of the method calls.
mystery0(7, 4);
10 4 5
mystery0(2, 2);
10 2 5
mystery0(5, 8);
5 8 6
mystery0(-1, -3);
10 -3 5

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

  • Copy/paste and save the following program in jGRASP, then see the instructions on the next slide.
    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... :*(");
            }
        }
    }
    

Exercise - things to fix

  • The program has a few syntax errors. Fix them until it compiles.
  • The code has a logic problem. (For some value(s), it prints the wrong answer.) Find any such problems and fix them. (You may need to run the program a few times and try different values to see which ones fail.)
  • The program uses if and else in a clumsy way. Improve the style of the code.

Exercise - answer

  • The following is a corrected version of the program:
    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... :*(");
            }
        }
    }
    

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.

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.

  • (Try solving this problem in Practice-It by clicking the icon above.)
  • For added challenge, try turning your solution into a second version pow2 that works with real number bases and negative exponents, as in book Exercise 4.11. practice-it

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

  • Download the following program icon FactorExample.java to your machine and open it with jGrasp.
  • The program's method has a few issues with external correctness and redundancy. Fix the code, and factor the method, restructuring the code to eliminate unnecessary statements while retaining the same behavior. This might involve changing conditional statements (ex. changing an if to an else if).
  • (When fixed,) running the program should produce the following output:

  • continued on the next slide...

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

  • Write a method named 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.
  • If the date falls between 12/16 and 3/15, you should return "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".
  • Try solving this problem in Practice-It! using the link 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!