1. Home
  2. Computing & Technology
  3. Java

The Infinite Loop

By , About.com Guide

Infinite Loop Solution

I'm not going to say there's a "right" way to rewrite the code. The key is to make the program function the same but to let the code leave the while loop logically, rather than making a sudden jump. If your code did that then well done!

Here's my version:

public class InfiniteLoopRewrite {

  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);

    //no longer an infinite loop..
    while (shouldLoopEnd == false)
    {
      //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;

      }
      else
      {
        // round the loop we go again
        System.out.println ("Let's try again..");

      }

    }

    System.out.println ("Woo hoo! We have a match!");

  }

} //end class
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.