Chapter 6: Controlling Program Flow with Loops 133 (Java hosting)
Chapter 6: Controlling Program Flow with Loops 133 the user gives the first response, the loop has nothing to check. The loop doesn t start with as long as such-and-such is true, then get a response from the user. Instead, the loop just leaps ahead, gets a response from the user, and then checks the response to see if it makes sense. That s why the program in Listing 6-4 has a do loop (also known as a do . . . while loop). With a doloop, the program jumps right in, takes action, and then checks a condition to see whether the result of the action makes sense. If the result makes sense, execution of the loop is done. If not, the program goes back to the top of the loop for another go-around. Listing 6-4: To Delete or Not to Delete import java.io.File; import static java.lang.System.out; import java.util.Scanner; class DeleteEvidence { public static void main(String args[]) { File evidence = new File( c:\cookedBooks.txt ); Scanner myScanner = new Scanner(System.in); char reply; do { out.print( Delete evidence? (y/n) ); reply = myScanner.findWithinHorizon( . ,0).charAt(0); } while (reply != y && reply != n ); if (reply == y ) { out.println( Okay, here goes… ); evidence.delete(); } else { out.println( Sorry, buddy. Just asking. ); } } } Figure 6-5 shows two runs of the code in Listing 6-4. The program accepts lowercase letters y and n, but not the uppercase letters Y and N. To make the program accept uppercase letters, change the conditions in the code as follows: do { out.print( Delete evidence? (y/n) ); reply = myScanner.findWithinHorizon( . , 0).charAt(0); } while (reply! = y && reply != Y && reply != n && reply!= N ); if (reply == y || reply == Y )
Would you like to be a member of headache free web site owner’s community. Now you can. We focus in IX Web Hosting, go go go!