How to Loop a Java Program With A Prompt

A Beginner’s Guide to User-Controlled Loops

Before You Start: How to Run Java Code

If you’ve never coded in Java before, follow these steps:

  1. Install Java:
  2. Install a Code Editor:
  3. Create Your First File:

Why This Matters

User interaction loops help create programs that:
Repeat actions until users are done
Handle errors gracefully
Build interactive experiences like games and tools

The Core Solution: while + Scanner

What this does: Creates a simple “Try Again?” prompt
How to use: Replace System.out.println("Running program...") with your actual code

javaimport java.util.Scanner;  // Required for user input

public class RetryLoop {
    public static void main(String[] args) {
        // Step 1: Create input scanner
        Scanner scanner = new Scanner(System.in);
        boolean retry;
        
        // Step 2: Create the retry loop
        do {
            // YOUR CODE GOES HERE - REPLACE THIS LINE!
            System.out.println("Running program...");
            
            // Step 3: Ask to continue
            System.out.print("Try again? (yes/no): ");
            String input = scanner.nextLine().trim().toLowerCase();
            retry = input.equals("yes");
            
        } while (retry);  // Step 4: Repeat if user says "yes"
        
        // Step 5: Clean up
        scanner.close();
    }
}

Key Features:
▸ Works for basic programs
▸ Easy to understand
▸ Requires no extra tools

Advanced Implementation: Error Handling

What this adds:

  • Number validation
  • Max 3 attempts
  • Clear error messages
javapublic class RetryWithLimits {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int maxAttempts = 3;  // Change to allow more/fewer tries
        int attempts = 0;
        boolean success = false;
        
        do {
            try {
                System.out.print("Enter a number (1-100): ");
                int num = Integer.parseInt(scanner.nextLine());
                
                if(num < 1 || num > 100) {
                    throw new IllegalArgumentException();
                }
                
                System.out.println("Valid number: " + num);
                success = true;
                
            } catch (Exception e) {
                System.out.println("Invalid input! Attempts left: " + (maxAttempts - attempts));
                attempts++;
            }
            
        } while (!success && attempts < maxAttempts);
        
        scanner.close();
    }
}

How to Modify:

  • Change maxAttempts to allow more tries
  • Adjust number range (1-100) in the if-statement

Pro Tips for Beginners

Test Your Code:

Try entering “YES”, “no”, and “maybe”

Test with numbers like 0, 50, and 101

Common Errors:

java// WRONG: Forgets to close scanner // scanner.close(); // WRONG: Uses wrong comparison // if(input == "yes") // Use .equals() instead!

Next Steps:

Add a score counter for games

Create multiple retry points

Add a delay between tries with Thread.sleep(1000)

Real-World Examples

Quiz Game:

java

do { askQuestion(); checkAnswer(); System.out.print("Next question? (yes/no): "); } while (scanner.nextLine().equalsIgnoreCase("yes"));

Data Entry Tool:

java

while (true) { try { enterData(); break; // Exit on success } catch (Exception e) { System.out.println("Error! Try again."); } }

Troubleshooting:
“Cannot find Scanner” error?
→ Ensure import java.util.Scanner; is at the top
Program closes immediately?
→ Use scanner.nextLine() instead of scanner.next()

Practice Exercise:
Create a password checker that:

  • Gives 3 attempts
  • Shows “Access granted” on correct input
  • Exits on too many failures

Need Help?
Java Installation Guide
VS Code Java Setup Tutorial
Official Java Tutorials

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top