You have to move the input.next() inside of the loop and I would recommand to use a while instead of a for loop:

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    String secret = "Please", guess = "";

    System.out.print("Secret word?");

    while (!guess.equals(secret)) {
        guess = input.next();

        if (guess.equals(secret)) {
            System.out.println("enter");
        } else {
            System.out.println("try again");
        }
    }
}
Answer from Josef Reichardt on Stack Overflow
🌐
Coderanch
coderanch.com › t › 691813 › java › Loop-program-user-input
While-Loop for ending program from user input (Beginning Java forum at Coderanch)
March 17, 2018 - The user is then given a 'grade' that depends on the value of the letter choices. The program will loop until the user chooses to quit and end the program. If the user gives an invalid input, (any other character or letter not A-F), the program will loop, asking for valid input until it's given.
🌐
Reddit
reddit.com › r/learnjava › how to loop until user gives correct input ?
r/learnjava on Reddit: How to loop until user gives correct Input ?
April 25, 2021 -

Hello, everyone.

I have currently started to learn Java and I am stuck at this problem.

How can I loop this bit-of code so that it repeats until user gives the correct Input ? The correct input is number (Integer).

I have tried using boolean and While loop, but I have created only an infinite loop.

 try {
     System.out.println("Enter age : ");
     newPerson.setAge(userInput.nextInt());
     userInput.nextLine();
} catch (Exception e) {
    System.out.println("Age must be number");
}
Discussions

java - Loop user input until conditions met - Stack Overflow
I need to ask the user to input a number to be used as the start of a range, and then input another number that is the end of the range. The start number has to be 0 or greater and the end number c... More on stackoverflow.com
🌐 stackoverflow.com
java - How to loop through until user inputs a valid integer? - Stack Overflow
I'm new to java and am trying to validate numbers being entered into the console. I want an integer, but I know if a letter is entered for example an error would occur, so I thought I'd use try & catch. This works if try and do it first time round, but I want to loop through until the user inputs a ... More on stackoverflow.com
🌐 stackoverflow.com
java - Unable to loop until valid value is entered - Stack Overflow
Though I am getting correct output but here I want to loop until valid value is entered ... Take a look at my solution below. ... Since you want to continuously receive a value until it is valid. It is an obvious hint you need to enclose your prompting of input within your loop: More on stackoverflow.com
🌐 stackoverflow.com
Looping Until the Value Passes - Java
Klaudia Krol is having issues with: Hi All, Could you please paste how this exercise should look like ?? I cannot pass this track and dont know where I am wrong . More on teamtreehouse.com
🌐 teamtreehouse.com
3
September 11, 2016
🌐
Programming Simplified
programmingsimplified.com › java › tutorial › java-while-loop
Java while loop | Programming Simplified
3. A body of a loop can contain more than one statement. For multiple statements, you need to place them in a block using {}. If the body contains only one statement, you can optionally use {}. It is always recommended to use braces to make your program easy to read and understand. Following program asks a user to input an integer and prints it until the user enter 0 (zero).
🌐
CodePal
codepal.ai › code-generator › query › xQ7ueuuE › java-user-input-validation
Java User Input Validation with Loops - CodePal
Please enter an integer."); scanner.nextLine(); // Clear the input buffer } } System.out.println("Valid input: " + userInput); } /** * Prompts the user for input until they provide a valid integer.
Find elsewhere
🌐
Engineering LibreTexts
eng.libretexts.org › bookshelves › computer science › programming languages › think java - how to think like a computer scientist (downey) › 15: loops
15.6: The do-while Loop - Engineering LibreTexts
December 1, 2020 - This type of loop is useful when you need to run the body of the loop at least once. For example, in Section 5.7 we used the return statement to avoid reading invalid input from the user. We can use a do-while loop to keep reading input until ...
🌐
Baeldung
baeldung.com › home › java › java io › read user input until a condition is met
Read User Input Until a Condition Is Met | Baeldung
January 8, 2024 - If the data match a defined condition, we stop reading input data. In practice, this condition can vary depending on the requirement. An idea to solve the problem is writing an infinite loop to keep reading user input line by line.
🌐
Java2s
java2s.com › example › java-book › input-validation-with-while-loop.html
Java - Input Validation with while loop
import java.util.Scanner; public class InputValidation { public static void main(String args[]) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number in the " + "range of 1 through 100: "); int number = keyboard.nextInt(); // Validate the input.
🌐
DataCamp
datacamp.com › doc › java › java-while-loop
Java While Loop
In this example, the while loop is used to validate user input. It continues to prompt the user until a valid number between 1 and 10 is entered.
🌐
Reddit
reddit.com › r/javaexamples › getting input from the console : validating and looping
r/javaexamples on Reddit: Getting Input from the Console : Validating and Looping
April 20, 2015 - Here is a more complicated example, using the other input method I discussed above, which uses a separate boolean method to validate. This program lets the user add integers one at a time, in a range specified in the code, until they type 'stop',then it adds them to a linked list, then sorts and displays them. import java.util.*; import java.io.*; public class Validate { public static String getInputLine(String prompt) { String inString = ""; try { // create buffered reader instance BufferedReader ibr = new BufferedReader( new InputStreamReader(System.in)); while (inString.equals("")) { System
🌐
Vik-20
vik-20.com › java › 1-10-the-do-while-loop
1-10 The do..while Loop – VIK-20.com
September 23, 2025 - The do..while loop is another type ... a post-test loop. Here’s an example that continuously prompts a user for an integer until they enter a value between 1 and 10 (inclusive)....
🌐
Unibz
inf.unibz.it › ~calvanese › teaching › 05-06-ip › lecture-notes › uni06 › node31.html
Example of a do loop: input validation
Often it is necessary to validate data input by the user, and repeat the request for the data in the case where the input of the user is not valid. This can be done by using a do loop. Example: Write a public static method that continues reading from input an integer until the integer is positive, ...
Top answer
1 of 2
1

In your final code example in the class called CalTest where you assign valX = input.nextDouble(); you could a call recursive method that handles the exception until the input is what you want. Something like this:

private static double getNextDouble(Scanner input) {
    try {
        return input.nextDouble();
    } catch (InputMismatchException e) {
        System.out.println("Value X must be a number: ");
        input.next();
        return getNextDouble(input);
    }
}

You'll replace valX = input.nextDouble(); with valX = getNextDouble(input);.

You can tidy this up and make it work for your other potential error cases, perhaps creating a parameter for the output message and passing it in as an argument.

2 of 2
-1
public static void main(String[] args) {
    double valX=0,valY=0;
    char operator='0';//dummy default

    Scanner input = new Scanner(System.in);
    System.out.println("Calculator Activated.");

    Double dX = null;
    do
    {
        System.out.print("Value X: ");
        dX = getDouble(input.next());
    }while (dX==null);
    {
        valX = dX;
    }

    Character op = null;
    do
    {
        System.out.print("Operator: ");
        op = getOperator(input.next());
    }while (op==null);
    {
        operator=op;
    }


    Double dY = null;
    do
    {
        System.out.print("Value Y: ");
        dY = getDouble(input.next());
    }while (dY==null);
    {
        valY = dY;
    }


    System.out.println("Done: "+ valX + " "+operator + " " +valY);
}

static Double getDouble(String input) {
    Double d = null;
    try {
        d = new Double(input);
    }catch(NumberFormatException ex){
    }
    return d;
}

static Character getOperator(String input) {
    Character c = null;
    if("+".equals(input) || "-".equals(input) || "*".equals(input) || "/".equals(input)){
        c = input.charAt(0);
    }
    return c;
}
Top answer
1 of 3
1

Start by assuming the input is valid (and set valid to true on every iteration of the loop). Only set valid to false when you encounter an exception (hopefully the one you raised).

do {
    valid = true;
    try {
        System.out.println("Enter wall height (feet): ");
        wallHeight = scnr.nextDouble();
        if (wallHeight <= 0) {
            throw new Exception("Invalid Input");
        }
    } catch (Exception e) {
        valid = false;
        System.out.println("Invalid Input");
    }
} while (!valid);

Note that you do not appear to need an exception here, as

do {
    valid = true;
    System.out.println("Enter wall height (feet): ");
    wallHeight = scnr.nextDouble();
    if (wallHeight <= 0) {
        System.out.println("Invalid Input");
        valid = false;
    }
} while (!valid);

would also work. Of course, that assumes the user only inputs valid double(s). If you need handle arbitrary input, you should check that there is a double before you attempt to consume it (and you must consume anything that isn't a double or you have an infinite loop). Like,

do {
    valid = true;
    System.out.println("Enter wall height (feet): ");
    if (scnr.hasNextDouble()) {
        wallHeight = scnr.nextDouble();
        if (wallHeight <= 0) {
            System.out.println("Invalid Input");
            valid = false;
        }
    } else {
        System.out.println("Invalid Input " + scnr.nextLine());
        valid = false;
    }
} while (!valid);
2 of 3
0

Here is another take.I just moved the code that sets valid = true after the if check. It can make it that far only when its valid. Otherwise valid will be false and it will loop.

public class BasicDoWhile {

    public static void main(String[] args) {
        double wallHeight = 0.0;
        boolean valid = false;

        Scanner scnr = new Scanner(System.in);

        // Implement a do-while loop to ensure input is valid
        // Prompt user to input wall's height
        do {
            try {
                System.out.println("Enter wall height (feet): ");
                wallHeight = scnr.nextDouble();

                if (wallHeight <= 0) {
                    throw new Exception("Invalid Input");
                }

                valid = true;

            }
            catch (Exception e) {
                System.out.println("Invalid Input");
            }

        } while (!valid);

    }
}
🌐
Delft Stack
delftstack.com › home › howto › java › java while loop user input
How to Implement Java while Loop With User Input | Delft Stack
March 11, 2025 - In this revised code, we attempt to convert the user input into an integer using Integer.parseInt(). If the conversion fails, a NumberFormatException is thrown, which we catch to inform the user that their input was invalid. This way, the program will keep running, allowing the user to try again until they either enter a valid number or type “exit” to quit. Another practical use of a while loop is to create a menu that allows users to select options. This can be particularly useful in applications where you want to provide multiple functionalities. Below is an example of a simple menu-driven program: import java.util.Scanner; public class MenuDrivenProgram { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int choice = 0; while (choice != 3) { System.out.println("Menu:"); System.out.println("1.