|
home—info—lects—labs—exams—hws
tutor/PIs—Object120 + its docs—java.lang docs—java.util docs
We ended last time with:
int i = 0; // Index variable: number of times through the loop while (i < 1000000) { System.out.println( "i is now " + i ); i = i+1; } |
Task (for you to do by hand):
What is the result of 0+1+2+3+4+…+9?
When you did this by hand, what information did you keep track of?
Let's write the process in pseudo-code: English instructions for your (perhaps rather dense) roommate to follow. Note that your roommate might get interrupted and stop to text a friend; they'll remember which instruction they're working on but won't remember anything else. Have them keep local variables to store any info they need to remember!
- Keep a variable i, which is currently zero. (Or, “nextNumToAdd”)
- Keep a variable sum-so-far, which is currently zero.
- While i is less than 10:
- Add i to sum-so-far, and make that the new sum-so-far.
- Add 1 i to i, and make that the new i.
- sum-so-far now contains your answer.
Note: If we want to time our loop, we can use java.lang.System#currentTimeMillis.
Example: “fingerprinting” a string.
Add up the character codes of each letter in
For a string
With a friend:
look up the documentation for
java.util.Random,
and use that class and its methods
to generate some random numbers in the Code Pad.
(Note that Java could have named the class more accurately as
“RandomNumberGenerator”,
since that's what the object actually is -- it's not itself a random object!)
Write a small function that just prints
three
random numbers in the range [-10,+10),
as well as the sum of those
three
numbers.
(Double-check that your answer is correct --
note that it's difficult to write automatic test cases
when using random numbers!)
(If you want to combine this problem with using a
java.util.Scanner
from last week's lab,
you can modify the problem to prompt the user for the upper and lower bound.)
home—info—lects—labs—exams—hws
tutor/PIs—Object120 + its docs—java.lang docs—java.util docs
©2010, Ian Barland, Radford University Last modified 2010.Oct.27 (Wed) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |