While LoopsΒΆ

A while loop is typically used when you don’t know how many times the loop will execute. You might use it while processing a string. Google has been scanning old books and then using software to read the scanned text. But, the software can get things mixed up like using 1 for l. The following code loops through a string replacing all 1’s with l’s.

String message = "Have a 1ong and happy 1ife";
int index = 0;

// while more 1's in the message
while (message.indexOf("1") >= 0)
{
   index = message.indexOf("1");
   message = message.substring(0,index) + "l" + message.substring(index+1);
}

The while loop starts on line 5 in the code above. Statements 7 and 8 are in the body of the loop (between the opening parenthesis on line 6 and the closing one on line 9). Please note that Java doesn’t require your code to be correctly indented (code moved to the right a few spaces) to make it clear what statements are part of the body of the loop, but it is good practice. On the free response part of the exam, the reader will use the indention when determining the meaning of your code, even if you forget the open or close curly brace.

One thing to be careful about with while loops is making sure that you don’t end up with an infinite loop. An infinite loop is one that never stops (the condition is always true).

// an infinite loop
while (true)
{
   System.out.println("This is the loop that never ends");
}

The infinite loop above is pretty obvious. But, most infinite loops are accidental. They usually occur because you forget to change the thing you are checking in the condition.

Check your understanding

6-3-1: What does the following code print?

int x = -5;
while (x < 0)
{
   x++;
   System.out.print(x + " ");
}




6-3-2: What are the values of var1 and var2 when the code finishes executing?

int var1 = 0;
int var2 = 2;

while ((var2 != 0) && ((var1 / var2) >= 0))
{
   var1 = var1 + 1;
   var2 = var2 -1;
}






6-3-3: What are the values in a after multAll(3) executes?

private int[ ] a = {1, 3, -5, -2};

public void multAll(int amt)
{
   int i = 0;
   while (i < a.length)
   {
      a[i] = a[i] * amt;
      i++;
   } // end while
} // end method





6-3-4: What are the values in a after mult(2) executes?

private int[ ] a = {1, 3, -5, -2};

public void mult(int amt)
{
   int i = 0;
   while (i < a.length)
   {
      a[i] = a[i] * amt;
   } // end while
} // end method





Mixed up programs

6-3-5: The following method has the correct code to return a string with all a's removed, but the code is mixed up. Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order or not indented correctly. The code will need to be correctly indented for your solution to be correct. To indent just drag the block to the right.