Web hosting unlimited bandwidth - 132 Part II: Writing Your Own Java Programs

132 Part II: Writing Your Own Java Programs enters a whileloop, the computer checks to make sure that the loop s condition is true. If the condition isn t true, the statements inside the loop are never executed not even once. In fact, you can easily cook up a while loop whose statements are never executed (although I can t think of a reason why you would ever want to do it). int twoPlusTwo = 2 + 2; while (twoPlusTwo == 5) { out.println( Are you kidding? ); out.println( 2 + 2 doesn t equal 5 ); out.print( Everyone knows that ); out.println( 2 + 2 equals 3 ); } In spite of this silly twoPlusTwoexample, the whilestatement turns out to be the most versatile of Java s looping constructs. In particular, the while loop is good for situations in which you must look before you leap. For example: While money is in my account, write a mortgage check every month. When you first encounter this statement, if your account has a zero balance, you don t want to write a mortgage check not even one check. But at times (not many), you want to leap before you look. Take, for instance, the situation in which you re asking the user for a response. Maybe the user s response makes sense, but maybe it doesn t. If it doesn t, you want to ask again. Maybe the user s finger slipped, or perhaps the user didn t understand the question. Figure 6-5 shows some runs of a program to delete a file. Before deleting the file, the program asks the user whether making the deletion is okay. If the user answers y or n, the program proceeds according to the user s wishes. But if the user enters any other character (any digit, uppercase letter, punctuation symbol, or whatever), the program asks the user for another response. Figure 6-5: Checking before you delete a file. To write this program, you need a loop a loop that repeatedly asks the user whether the file should be deleted. The loop keeps asking until the user gives a meaningful response. Now, the thing to notice is that the loop doesn t need to check anything before asking the user the first time. Indeed, before
The UK has been a member of the European Union since 1973. The attitude of the present government towards further integration is conservative, with the official opposition favoring a return of some powers and competencies to the UK.From our experience, we can recommend Cheap UK Web Hosting services.

Leave a Reply