|
home—info—archive—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
Exercise: Complete the following, using a for-each loop:
/** Return the number of Widgets in a list-of-Widgets. * Our method will work even if the List method "size()" is broken/missing. * @param things The list of items to count. * @return the number of Widgets in `things`. */ public static int mySize( java.util.LinkedList<Widgets> things ) { } |
In our solution, our “so-far” variable is just tracking how many items we've already seen (processed). Note that this is the same as tracking the index of the item we'll look at next.
Over the next week, we'll look at two other types of loops — while loops and for loops (as opposed to for-each loops); we will routinely keep track of such an index manually, in addition to any other information we accumulate.
Here is the source code for this week's lectures: lect12-loop-practice, lect12-loop-practice.jar. (how-to-get-jar-files-into-BlueJ—Downloading .jar files into BlueJ)
For-each loops are nice when we have a list to process (and, we want to handle each element in exactly the same way). But what about when we want to do something over-and-over, but we don't have a list? For example: We want to play a game of volleyball -- keep playing a single point, until the game is over. Recall/review the methods we wrote back in hw03soln-VolleyballJudge.html.
/** Play one game of volleyball, and say which team one. * @return Whether or not the first team won. */ public boolean playOneGame() { int score1 = 0; int score2 = 0; while (! this.isGameOver(score1,score2) ) { // ...play one point... } // When we reach this line, we know the game is over -- *somebody* has won! return this.hasFirstTeamWon(score1,score2); } |
class VolleyballJudge { // A field: private java.util.Random randNumGenerator = new java.util.Random(); /** Play one game of volleyball, and say which team one. * @return Whether or not the first team won. */ public boolean playOneGame() { int score1 = 0; int score2 = 0; while (! this.isGameOver(score1,score2) ) { // Play one point: // Choose a random team to get a point, with 50/50 odds: if (randNumGenerator.nextDouble() < 0.50) { score1 = score1 + 1; } else { score2 = score2 + 1; } } // When we reach this line, we know the game is over -- *somebody* has won! return this.hasFirstTeamWon(score1,score2); } |
Another example of a while loop:
We saw earler, that if we have a source of characters (like the keyboard),
we can make a java.util.Scanner who can take those individual
characters and turn them into numbers (ints or doubles) or strings for us,
with the method nextInt(), nextDouble(),
next() (which returns the next word, as a string).
There are other useful
Scanner
methods: nextLine() which returns the entire
next line (a String),
as well as
a boolean method hasNext(), which
determines whether the source of characters has run dry.
/** Open up a URL, and read the input. * As a side-effect (for demonstration only), print each line to the console. * @return The number of lines in a given URL. */ public static int countLines() throws java.net.MalformedURLException, java.io.IOException { String sourcePage = "http://www.radford.edu/itec120/2008spring/"; // Open sourcePage for input: (Create a URL object based on sourcePage, open that URL as a stream-of-characters, // and create a Scanner who will group that stream's characters into Strings etc.) java.util.Scanner src = new java.util.Scanner( new java.net.URL( sourcePage ).openStream() ); int linesSoFar = 0; // Keep track of how many lines we've seen. while ( src.hasNext() ) { src.nextLine(); // Have the scanner consume the next line. We ignore its return value. linesSoFar = linesSoFar + 1; } return linesSoFar; } |
The syntax of a while loop is what you'd expect from the above example:
What does the following method return?
/** Announce a countdown, starting at 10. * @return A countdown starting at 10. * That is, "10...9...8... [etc] 2...1...Liftoff!" */ public String countdown() { String chantSoFar = ""; /* A local variable, to accumulate the answer. */ int t = 10; /* The next number to count down. */ while (t >= 0) { chantSoFar = chantSoFar + (t + "..."); t = t-1; } return (chantSoFar + "Liftoff!"); } |
style tip: Don't just make the parameter named t and then assign to it (but mention that approach). Keeping the parameter untouched segues well into the next problem.
home—info—archive—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
©2008, Ian Barland, Radford University Last modified 2008.Apr.07 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |