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
Goals for today:
return
values to send data between methodsif
, else if
and else
to have
different branches of executionScanner
to create interactive programs that read user
inputString
s to represent and manipulate text dataA 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
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
|
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
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
.
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);
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum = sum + i;
}
System.out.println(sum); // 5050
Scanner
sumCopy 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
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.
repl
that accepts a String
and a number of repetitions as parameters and returns
the String
concatenated that many times. For example, the
call repl("hello", 3)
returns "hellohellohello"
. If the number of repetitions is 0
or less, an empty string is returned.
if/else
StatementsAn 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."); }
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 |
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); } |
|
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... :*("); } } }
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
.
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...
value
printHailstoneMaxMin(7, 10);
value
as the loop executes.
# |
value
|
---|---|
first value |
7
|
second value |
22
|
third value |
11 |
fourth value |
34 |
fifth value |
17 |
sixth value |
52 |
continued on the next slide...
min
printHailstoneMaxMin(7, 20);
min
during the second call.
# |
min
|
---|---|
first value |
7
|
second value |
5 |
third value |
4 |
fourth value |
2 |
fifth value |
1 |
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.
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.
"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"
.
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 |
String
methodsMethod name | Description |
---|---|
charAt(index)
|
character at given index |
indexOf(str)
|
index where the start of the given String appears in this
string (-1 if not found)
|
length()
|
number of characters in this String
|
replace(str1, str2)
|
a new string with all occurrences of str1 changed to str2 |
substring(index1, index2) or substring(index1) |
the characters in this string from index1 (inclusive) to index2 (exclusive); if index2 is omitted, grabs till end of string |
toLowerCase()
|
a new string with all lowercase letters |
toUpperCase()
|
a new string with all uppercase letters |
Write the results of each expression with String
s in
"quotes" and characters in single quotes ('a'
)
// index 0123456789012345
String str1 = "Frodo Baggins";
String str2 = "Gandalf the GRAY";
str1.length() |
13 |
|
str1.charAt(7) |
'a' |
|
str2.charAt(0) |
'G' |
|
str1.indexOf("o") |
2 |
|
str2.toUpperCase() |
"GANDALF THE GRAY" |
|
str1.toLowerCase().indexOf("B") |
-1 |
|
str1.substring(4) |
"o Baggins" |
|
str2.substring(3, 14) |
"dalf the GR" |
|
str2.replace("a", "oo") |
"Goondoolf the GRAY" |
|
str2.replace("gray", "white") |
"Gandalf the GRAY" |
|
"str1".replace("r", "range") |
"strange1" |
Copy/paste and save 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 ...
Type your name: Jessica Miller
Your name is: Miller, J.
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!