Back to Articles
Java10 min read

Understanding Loops in Java

Why loops keep games and apps running smoothly, how for, while, and do-while loops work, and a mini number-guessing project.

By Bisrat Ayalew

North Garland H.S. Chapter

Ever wonder how video game characters move smoothly instead of teleporting everywhere? That's mostly because of loops.

Loops let computers repeat actions without programmers writing the same line of code over and over again. Without loops, games, apps, and basically all software would be a mess.

What Is a Loop?

A loop is just a way to repeat code. An iteration.

In Java, loops keep running as long as a condition is true.

Example: imagine you're a teacher with 25 students. You wouldn't want to type "call on student" 25 different times. With a loop, you write it once and tell the computer to repeat it 25 times. Way easier.

Types of Loops in Java

Java has three main loops.

For Loops

Use a for loop when you know how many times something should run.

for (int i = 1; i <= 5; i++) {
    System.out.println("Number: " + i);
}

This starts at 1, prints the number, adds 1 each time, and stops once it hits 5.

While Loops

A while loop keeps running as long as the condition is true. This is good when you don't know how many times the loop will run.

int attempts = 0;
while (attempts < 3) {
    System.out.println("Attempt number: " + attempts);
    attempts++;
}

Do-While Loops

A do-while loop always runs at least once, no matter what.

int number = 0;
do {
    System.out.println("This runs at least once!");
    number++;
} while (number < 0);

Even though the condition is false, the code still runs once.

Where Loops Are Used

Loops are everywhere:

  • Games: movement, physics, and player input
  • Apps: refreshing feeds and checking notifications
  • Data: going through tons of information
  • Servers: staying on 24/7 waiting for users

Common Mistakes

Infinite loops: forgetting to update the variable

int i = 0;
while (i < 10) {
    System.out.println(i);
}
  • Off-by-one errors: starting or ending at the wrong number
  • Using the wrong loop: sometimes a while loop is just clearer than a for loop

Mini Project: Number Guessing Game

A number guessing game is a simple way to use loops. The program picks a random number, and you keep guessing until you get it right or run out of tries.

It uses:

  • While loops to keep the game running
  • For loops to count attempts
  • Do-while loops to make sure input actually makes sense
import java.util.Scanner;
import java.util.Random;

public class NumberGuessingGame {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();
        boolean playAgain = true;

        System.out.println(" WELCOME TO THE NUMBER GUESSING GAME ");
        System.out.println("Learn Loops While Having Fun!");
        System.out.println();

        do {
            playGame(scanner, random);

            String response;
            do {
                System.out.print("\nWould you like to play again? (yes/no): ");
                response = scanner.nextLine().trim().toLowerCase();

                if (!response.equals("yes") && !response.equals("no")) {
                    System.out.println("Please enter 'yes' or 'no'.");
                }
            } while (!response.equals("yes") && !response.equals("no"));

            playAgain = response.equals("yes");

            if (playAgain) {
                System.out.println("\n" + "=".repeat(40) + "\n");
            }

        } while (playAgain);

        System.out.println("Thanks for playing! Goodbye!");
        scanner.close();
    }

    public static void playGame(Scanner scanner, Random random) {
        int secretNumber = random.nextInt(100) + 1;
        int maxAttempts = 7;
        int attempts = 0;
        boolean hasGuessed = false;

        System.out.println("I'm thinking of a number between 1 and 100");
        System.out.println("You have " + maxAttempts + " attempts to guess it!");
        System.out.println();

        while (attempts < maxAttempts && !hasGuessed) {
            attempts++;

            System.out.print("Attempts remaining: ");
            for (int i = 0; i < (maxAttempts - attempts + 1); i++) {
                System.out.print(" ");
            }
            System.out.println("(" + (maxAttempts - attempts + 1) + " left)");

            int guess = getValidGuess(scanner, attempts);

            if (guess == secretNumber) {
                hasGuessed = true;
                displayVictory(attempts, maxAttempts);
            } else if (guess < secretNumber) {
                System.out.println("Too low! Try a higher number.");
                giveHint(secretNumber, guess);
            } else {
                System.out.println("Too high! Try a lower number.");
                giveHint(secretNumber, guess);
            }

            System.out.println();
        }

        if (!hasGuessed) {
            System.out.println("You've run out of attempts!");
            System.out.println("The number was:" + secretNumber);
        }
    }

    public static int getValidGuess(Scanner scanner, int attemptNumber) {
        int guess = -1;

        do {
            System.out.print("Attempt #" + attemptNumber + " - Enter your guess: ");

            if (scanner.hasNextInt()) {
                guess = scanner.nextInt();
                scanner.nextLine();

                if (guess < 1 || guess > 100) {
                    System.out.println("Enter a number between 1 and 100!");
                    guess = -1;
                }
            } else {
                System.out.println("That's not a valid number! Try again.");
                scanner.nextLine();
            }
        } while (guess == -1);

        return guess;
    }

    public static void giveHint(int secretNumber, int guess) {
        int difference = Math.abs(secretNumber - guess);

        if (difference <= 5) {
            System.out.println("You're very close! Almost there!");
        } else if (difference <= 15) {
            System.out.println("You're getting warm!");
        } else if (difference <= 30) {
            System.out.println("You're cold!");
        } else {
            System.out.println(" You're freezing! Way off!");
        }
    }

    public static void displayVictory(int attempts, int maxAttempts) {
        System.out.println("CONGRATULATIONS!");
        System.out.println("You guessed the number!");
        System.out.println();

        System.out.print("Your Rating: ");

        if (attempts <= 3) {
            System.out.print("AMAZING! ");
        } else if (attempts <= 5) {
            System.out.print("GREAT! ");
        } else if (attempts <= 6) {
            System.out.print("GOOD! ");
        } else {
            System.out.print("Nice! ");
        }

        System.out.println("(" + attempts + "/" + maxAttempts + " attempts)");
    }
}