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
Goals for today:
if/else
statements to select between alternate code pathsScanner
to read user inputString
s to represent and manipulate text dataif/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. 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
mystery
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
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.
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; } }
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:
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);
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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class StringOops { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Type your name: "); String name = console.nextString(); process(name); } public static void process(string "name") { if (name == Whitaker) { System.out.println("You must be really awesome."); } replace("a", "e"); toUppercase(name); name.substring(0, 3); System.out.println(name + " has " + name.length + " letters"); } } |
nextString
should be next
string
should be String
name
should not be in quotesWhitaker
should be in quotes==
; must
use .equals
replace
without specifying a string
object (name
)toUppercase
should be
toUpperCase
name.
should come
before toUpperCase
, not passed as a parameter to itname =
to store the result
of toUpperCase
name =
to store the result
of substring
()
when
calling length
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"); } }
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum = sum + i;
}
System.out.println(sum); // 5050
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.
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!
swapPairs
that accepts
a String
as a parameter and returns that String
with each pair of adjacent letters reversed. If the String
has an odd number of letters, the last letter is unchanged. For example,
the call swapPairs("forget")
should
return "ofgrte"
and the call swapPairs("hello
there")
should return "ehll ohtree"
.
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 |
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 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!