1. Technology

The Infinite Loop


Level: Beginner

Focus: Loops, random numbers

Infinite Loop Question

The code below uses a combination of an infinite loop and a break statement. The while loop's condition has been set so that it is always true. The only way out of the loop is to use a break statement to jump beyond its boundaries.

 public class InfiniteLoop {
   public static void main(String[] args) {
     //boolean variable to determine if the loop     //should end
     boolean shouldLoopEnd = false;
     //generate a random number 
     int targetNumber = (int) (Math.random() * 10);
     System.out.println ("The target number is: " + targetNumber);
     //infinite loop begins...
     while (true) 
       //generate a random number to try       //and match the target number
       int guessNumber = (int) (Math.random() * 10);
       System.out.println ("The loop guesses: " + guessNumber);
       //check to see if the guess is correct
       if (guessNumber == targetNumber) 
         shouldLoopEnd = true;
       //if we've guessed correctly break loop
       if (shouldLoopEnd == true)       {
         System.out.println ("Woo hoo! We have a match!");
         break; // break loop
         //around the loop we go again
         System.out.println ("Let's try again..");

Personally, I use the break statement as a last resort because it breaks the logical flow of a program and makes it harder to read. Can you rewrite the above code so that the program still works the same but it no longer uses the break statement?

To get the most out of this question try and figure out the answer before coming back to read the solution on the next page.

  1. About.com
  2. Technology
  3. Java
  4. Programming Exercises
  5. Beginner Level
  6. The Infinite Loop

©2014 About.com. All rights reserved.