|
home—info—lects—labs—exams—hws
tutor/PIs—breeze (snow day)
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 usejava.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
(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
home—info—lects—labs—exams—hws
tutor/PIs—breeze (snow day)
Object120 + its docs—java.lang docs—java.util docs
©2012, Ian Barland, Radford University Last modified 2012.Oct.24 (Wed) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |