Real World XML (2nd Edition)

Java Loops : for , while , do while

The next step after working with conditional statements is to handle loops. Like JavaScript, Java supports a for loop, a while loop, and a do...while loop.

Here's how you use a Java for loop in general, Note that the statement that makes up the body of the for loop can be a compound statement; it can be made up of several single statements enclosed in curly braces:

for ( initialization_expression; end_conditon; iteration_expression ) { statement }

You place an expression in the initialization part of the for loop (which often initializes a variablethat is, a loop indexto ), and then you place a test condition in the test part of the loop that is tested each time the code in the loop executes. If the test is false , the loop ends (often the test condition checks whether the value in the loop index exceeds a specified maximum value). On the other hand, if the test condition is true , the body of the loop is executed and the code in the increment part of the loop is executed to get the loop ready for the next iteration (often by incrementing the loop index).

Here's an example. In this case, I'm summing the values in five bank accounts, as stored in an array named accounts , using a for loop:

Listing ch10_10.java

public class ch10_10 { public static void main(String[] args) { double accounts[] = {365.55, 789.19, 532.11, 1079.96, 185.19}; double sum = 0; for (int loopIndex = 0; loopIndex < accounts.length; loopIndex++) { sum += accounts[loopIndex]; } System.out.println("The total in all accounts is $" + sum); } }

Here are the results of this code:

%java ch10_10 The total in all accounts is 52

Java also supports a while loop. I'll create an example showing how to use this loop and how you can read input from the keyboard. In this case, I'll keep reading from the keyboard until the user types the word quit .

You can use the System.in.read method to read character by character from the keyboard. This method waits until the user presses Enter at the end of the line, at which point Java stores all those typed characters . When you call this method, it reads the next character from those that were typed and returns it.

To read what the user has typed using this method, I'll start by creating a string named input . I'll add all the waiting characters to this string in succession by repeatedly calling the System.in.read method and then searching the string for the word quit . I can use the String class's indexOf method to search this string for that word and keep looping until that word is found. The indexOf method returns either the starting location of the string you're searching for or -1 if that string is not found. Here's how I can keep waiting for quit until it's found:

public class ch10_11 { public static void main(String[] args) { String input = ""; while (input.indexOf("quit") < 0){ . . . } } }

Each time the user enters a new line, I can use System.in.read to read the characters the user has typed and add them one by one to the input string. The System.in.read method actually returns ASCII codes as integers, so we'll need an explicit cast, (char) , to convert those values to characters that we can add to the input string.

The creators of Java knew that I/O operations are prone to errors, so they allowed the System.in.read to generate errors that your program can handle, called trappable errors or exceptions in Java. Generating such an error is called throwing an exception. You must enclose the code that can cause errors in a special construct called a try block:

public class ch10_11 { public static void main(String[] args) { String input = ""; while (input.indexOf("quit") < 0){ try { input += (char) System.in.read(); } . . . } } }

You follow the try block with a catch block to catch any errors that occurred. The catch block is passed an object of class Exception , and I'll name that object e here. I can use that object's printStackTrace method to display the error that occurred, sending the text from that method to the System.err output channel (which corresponds to the console by default) like this:

Listing ch10_11.java

public class ch10_11 { public static void main(String[] args) { String input = ""; while (input.indexOf("quit") < 0){ try { input += (char) System.in.read(); } catch (Exception e) { e.printStackTrace(System.err); } } } }

That's all we need, Now the user can enter text, which the application will read. When the user types the word quit anywhere in that text, the application will terminate:

%java ch10_11 Hi there! This is great. Anything happening? Well, looks like it's time to quit.

Not badnow we've seen one way to read from the keyboard as well as use the while loop.

Категории