|
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
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; System.out.println( "t is now " + t ); System.out.println( "chantSoFar is now " + chantSoFar ); } 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 will be more important in some future problems.
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.
We'll talk about the following program, which repeatedly: reads a line from a web page, and increments a variable “linesSoFar”. That is, the method counts the lines in a web page! Everything in gray is something you don't need to know right now.
/** 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/2009spring/"; // 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; } |
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
©2009, Ian Barland, Radford University Last modified 2009.Mar.30 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |