if/else
, Scanner
,
and return
if/else
, Scanner
,
and return
Except where otherwise noted, the contents of this document are Copyright 2010 Stuart Reges and Marty Stepp.
lab document created by Whitaker Brand and Marty Stepp
Goals for today:
return
values to send data between methods
Scanner
to create interactive programs that read
user input
if/else
statements to select between multiple
code actions
The scores you receive on homework and lab assignments are available for you to view in MyUW. Follow the instructions on this page to check your scores. For each lab, there is an attendance score and a homework score. Because this is lab 4, you shouldn't expect to see scores yet for lab 3, but you should see scores for labs 1 and 2. You need to get credit for both attendance and homework to get credit for a lab. Make sure that you have scores for lab 1 and lab 2. If you don't have credit and you think you should, contact the head TA managing the labs, Will Beebe (nedrager@cs.washington.edu).
Using the information on your MyUW page, fill in the values below.
class mean for a1 (i.e., average score for assignment 1) |
8.81 |
|
class mean for lab1 (i.e., average score for lab 1) |
0.98 |
In lecture we wrote 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; }You are going to write a similar method for performing a particular mathematical computation. Write a method called
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 computes
as pi times the radius squared and that Java has a constant
called Math.PI
.
Scanner
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...
Scanner
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.
if
/else
mysteryConsider 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); } |
|
if
/else
mysteryConsider the following Java code.
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 |
if
/else
mysteryConsider the following Java code.
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 |
Write a method named pay
that accepts a real number for a TA's
salary and an integer for the number of hours the TA worked this week, and
returns 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
. For example:
if (x < 30) { a = 2; x++; System.out.println("CSE 142 TAs are awesome! " + x); } else { a = 2; System.out.println("CSE 142 TAs are awesome! " + x); }
else
went away!)
a = 2; if (x < 30) { x++; } System.out.println("CSE 142 TAs are awesome! " + x);
if
/else
Factoringmain
and run it to make sure it works properly.
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.
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.
Write a method named smallestLargest
that prompts the user to
enter numbers, reads them, then prints the smallest and largest of all the
numbers typed in by the user. For example:
How many numbers do you want to enter? 4 Number 1: 5 Number 2: 11 Number 3: -2 Number 4: 3 Smallest = -2 Largest = 11
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... :*("); } } }
AgeCheck
program's message
method with:
// Possibly prints some message(s) to the user based on the given age public static void message(int age) { if (age >= 21) { System.out.println("I can legally purchase alcohol!"); } else if (age >= 17) { System.out.println("I can purchase a ticket to an R-rated movie."); } else if (age >= 16) { System.out.println("I can get my driver's license!"); } }
if
s
and else
s in this method to behave properly.
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; } }
Write a complete program WazzuAdmit
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 of 1.8 or an SAT score of
900 or above (or both) will cause the student to be accepted; anything less
will cause him/her to be rejected.
Washington State University admission program What is your GPA? 3.2 What is your SAT score? 1280 You were accepted!
import java.util.*; // for Scanner public class WazzuAdmit { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.println("Washington State University admission program"); System.out.print("What is your GPA? "); double gpa = console.nextDouble(); System.out.print("What is your SAT score? "); int sat = console.nextInt(); if (gpa >= 1.8 || sat >= 900) { System.out.println("You were accepted!"); } else { System.out.println("You were rejected!"); } } }
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:
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 Chapter 4 and try to solve them!