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:
String
s to represent and manipulate text datawhile
loops for indefinite repetitionA 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
Write a method named 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 fewer, an empty string is returned.
(Hint: This is best solved with a cumulative algorithm. Start with an
empty string and build it up piece by piece.)
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!
In this exercise we will download a program from the textbook for a debugging exercise.
Hailstone.java
.
Right-click the file name and choose the option to Save the Link in the folder you have been using for lab work.
Hailstone.java
in jGRASP.
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. You may have to step through several iterations until you get to a distinct value of min
.
# |
min
|
---|---|
first value |
7
|
second value |
5 |
third value |
4 |
fourth value |
2 |
fifth value |
1 |
A fencepost loop is a common algorithmic pattern where you want to perform N tasks with N-1 things between them. It's like a fence with N posts with N-1 wires between the posts.
To achieve this, place one "post" outside your loop, then alternate between "wires" and "posts" inside the loop.
Example:
System.out.print(1); // |==|==|==|==| fence for (int i = 2; i <= 5; i++) { System.out.print(".." + i); // 1..2..3..4..5 }
printLetters
that takes a String
as its parameter and that prints the letters of the String, separated by dashes.
For example, the call of printLetters("Rabbit")
should print:
R-a-b-b-i-t(Hint: This is a fencepost problem. Remember that each
String
object has a length
method that tells you how many characters are in the String
and a charAt
method that gets you individual characters of
the String
.)
Write a method called printFactors
that accepts an integer as its parameter and that prints the factors of that number, separated by the word "and"
. Recall that a factor is a number that goes evenly into another number.
For example, the call printFactors(24)
should print the following output:
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
You may assume that the parameter value passed is greater than 0.
while
Loops
for
loops are fantastic for when we know how many times we want to repeat something. But sometimes we won't know how many times we'll want to repeat something in advance! while
loops repeat indefinitely while a given condition is true.
while (test) { statement(s); }
Example:
int num = 1;
while (num < 5) {
System.out.print(num + " "); // output: 1 2 3 4
num++;
}
while
loop basicsConsider the following loop.
int x = 1; System.out.print(x); while (x < 100) { x = x + x; System.out.print(", " + x); }
How many times does the code in the while loop execute?
|
7 |
What output is produced by the overall code? | 1, 2, 4, 8, 16, 32, 64, 128 |
while
loop mystery
Fill in the boxes at right with the output produced by each method call.
public static void mystery(int x) { int y = 1; int z = 0; while (2 * y <= x) { y = y * 2; z++; } System.out.println(y + " " + z); } |
|
while
loop mystery
Fill in the boxes at right with the output produced by each method call.
public static void mystery2(int x, int y) { int z = 0; while (x % y != 0) { x = x / y; z++; System.out.print(x + ", "); } System.out.println(z); } |
|
Write a method named digitSum
that accepts an integer as a parameter and returns the sum of the digits of that number.
For example, the call digitSum(29107)
returns 2+9+1+0+7 or 19.
For negative numbers, return the same value that would result if the number were positive.
For example, digitSum(-456)
returns 4+5+6 or 15.
The call digitSum(0)
returns 0.
(Hint: This is a cumulative algorithm. To extract a digit from a number, use / 10
and % 10
operations.)
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!