Doing the DoWhile Thing

Doing the Do/While Thing

A do / while statement is like a while statement except that the expression is evaluated after the statement has been executed rather than before. You can think of this as testing at the bottom of the loop rather than the top. The impact is to ensure that the statement in a do / while statement is executed at least once, even if the condition evaluates to false.

The general form of the do/while statement is as follows:

 do     statement  while (condition); 

As with while loops, you can replace the single statement in this syntax with a statement block, provided you put the statements in the block with curly braces:

 do  {     statement1;     statement2;     ...     statementn;  }  while (condition); 

Try This at Home

To see how easy it is to use while statements, let’s go ahead and rewrite the program that reverses a string using a do / while loop instead of a for statement.

To Create a Do/While Loop That Reverses Text Entered by the User:

Do It Right!
  1. Create the framework for a script within the body of an HTML document:

     <HTML> <BODY> <H1> <SCRIPT> </SCRIPT> </H1> </BODY> </HTML> 

  2. Create the scaffolding for the do/while statement:

     do    {    }  while (); 

  3. Initialize a variable before the do/while statement to hold the value of the reversed text string:

     var newString = ""; 

  4. Use the prompt function to obtain a string from the user:

     var newString = "";  var theString = prompt("Enter a string for reversal",""); 

    When the prompt function runs, the user will be prompted for input as shown in Figure 4-5.

    click to expand
    Figure 4-5: The user is prompted for a text string to reverse.

  5. Use the length property of theString to store the length of the string in a counter variable:

     var theString = prompt("Enter a string for reversal","");  var counter = theString.length; 

  6. Create the expression for the do/while statement:

     var newString = "";  var theString = prompt("Enter a string for reversal","");  var counter = theString.length;  do    {    }  while (counter > 0 ); 

    In this case, the conditional statement means that the statement will stop being processed when the counter variable, which is the length of the string the user entered, is zero.

  7. Enter the statement to be executed:

     do    {       newString += theString.substring(counter-1, counter);    } 

  8. Decrement the counter:

     do    {       newString += theString.substring(counter-1, counter);       counter--;    } 

    Decrementing the counter ensures that the loop will terminate and enables the reversal process to work.

  9. Add a statement after the do/while loop to print the results:

     document.write(theString + " reversed is " + newString + "!"); 

  10. Run the program. After the user enters a text string as shown in Figure 4-5 and clicks OK, the reversed string is displayed (see Figure 4-6). Listing 4-3 shows the complete code used.

    Listing 4.3: Using a Do/While Loop to Reverse a Text String

    start example
     <HTML> <BODY> <H1> <SCRIPT>        var newString = "";        var theString = prompt("Enter a string for reversal","");        var counter = theString.length;        do        {          newString += theString.substring(counter-1, counter);          counter--;        }        while (counter > 0 );        document.write(theString + " reversed is " + newString + "!");     </SCRIPT> </H1> </BODY> </HTML> 
    end example

    click to expand
    Figure 4-6: The reversed text string is displayed.

Of course, the two programs (one shown in Listing 4-1 using a for loop and the other shown in Listing 4-3 using a do / while loop) aren’t different except at the heart—the loops.

So, it’s a good idea to look closely at the essential difference between the two programs. Behind door number one, we have the do/while loop:

 do  {    ...    counter --;  }  while (counter > 0 ); 

Here’s the door number two entrant, the for loop:

 for (counter  ;counter > 0 ;counter -- )  {  ...  } 

Can you see how these two loops amount to the same thing?

Whichever loop you use, neither program is really that polished.

Do It Right!

In the real world, you’d probably want to add some niceties to the program. For example, you should check the input string to make sure the user hasn’t pressed Cancel in the prompt box. Otherwise, the variable theString will not have a string stored in it, and the following statement:

 var counter = theString.length; 

will cause a JavaScript syntax error when the program runs. To see this error, try running the program and clicking Cancel in the prompt box. A blank browser window will open, and if you look on the browser’s status bar, you’ll see a message like that shown in Figure 4-7 (this figure shows the error message in Internet Explorer; it will look slightly different in other Web browsers).

click to expand
Figure 4-7: If you try to assign the length property of an empty object, you’ll get a syntax error.

To get a more complete explanation of the error, you can double-click the icon in the browser status bar. You’ll get an explanatory message describing the error and providing a line number where it occurred, like that shown in Figure 4-8.

click to expand
Figure 4-8: The Web browser provides an explanation of JavaScript errors and the line number in the program where they occurred.

Another problem you might want to handle is the case of a user who inputs an empty string. As things stand now, you’ll get the display shown in Figure 4-9, which isn’t incorrect but somewhat sloppy. It’d be better to display a message such as “You didn’t enter any text to reverse. Please try again by clicking the Refresh button on your browser.”

click to expand
Figure 4-9: If the user enters an empty string, the browser display looks kind of weird.

For more on error handling, debugging, and writing code that’s not error-prone, see Chapter 10, “ Error Handling and Debugging.”

Learn How to Program Using Any Web Browser
Learn How to Program Using Any Web Browser
ISBN: 1590591135
EAN: 2147483647
Year: 2006
Pages: 115
Authors: Harold Davis

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: