1. Home
  2. Computing & Technology
  3. Java

The Infinite Loop

By , About.com Guide

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
      }
      else
      {
        //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.

Explore Java
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Java
  4. Programming Exercises
  5. Beginner Level
  6. The Infinite Loop >

©2009 About.com, a part of The New York Times Company.

All rights reserved.