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
🌐
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 & 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
Java Wrong Input For Vector Loop Until Correct - Stack Overflow
I need to place in a selected by User input quantity, numbers that are only in between 1 and 60, values less than 1 and more than 60 should be invalid... And asked for a new input. Thing is, I don'... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.
🌐
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 - In this article, we’ve explored how to write a Java method to read user input until a condition is met.
🌐
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 ...
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 65366934 › java-wrong-input-for-vector-loop-until-correct › 65367060
Java Wrong Input For Vector Loop Until Correct - Stack Overflow
int c=0; while(c<bets.length){ System.out.println("Choose a number "); int input = teclado.nextInt(); if ((input < 1) || (input > 60)) { System.out.println("Only 1 to 60 values."); continue; } bets[c]=input; c++; }
🌐
Programming Simplified
programmingsimplified.com › java › tutorial › java-while-loop
Java while loop | Programming Simplified
In Java, a while loop is used to execute statement(s) until a condition is true. In this tutorial, we learn to use it with examples.
🌐
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. * Uses a while loop.
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);

    }
}
Top answer
1 of 4
2

At a very simple level, I'd use a do-while loop, as you want to enter the loop at least once. I'd then determine the validity of the input, using a boolean flag and make further determinations based on that, for example...

Scanner myScan = new Scanner(System.in);
boolean userInputCorrect = false;
String food = null;
do {
    System.out.println("Enter food");
    food = myScan.nextLine();
    userInputCorrect = food.equalsIgnoreCase("b") || food.equalsIgnoreCase("e") || food.equalsIgnoreCase("exit");
    if (!userInputCorrect) {
        System.out.println("Error");
    }
} while (!userInputCorrect);
System.out.println("You selected " + food);

An expanded solution might use some kind of valid method, into which I can pass the String and have it validate the input based on known values, but that's probably a little beyond the scope of the question

As has been, correctly, pointed out but others, it would be more efficient to convert the input to lowercase once and compare all the values, in this case, it might be better to use a switch statement...

Scanner myScan = new Scanner(System.in);
boolean userInputCorrect = false;
String food = null;
do {
    System.out.println("Enter food");
    food = myScan.nextLine();
    switch (food.toLowerCase()) {
        case "b":
        case "e":
        case "exit":
            userInputCorrect = true;
            break;
        default:
            System.out.println("Error");
    }
} while (!userInputCorrect);
System.out.println("You selected " + food);

But you could also do...

food = myScan.nextLine().toLowerCase();
userInputCorrect = food.equals("b") || food.equals("e") || food.equals("exit");
2 of 4
1

One approach would be to define a "flag" variable, then loop until it's "true". For example:

  Scanner myScan = new Scanner(System.in);
  boolean done = false;
  while (!done) {                                        
    System.out.println("Enter food");                                       
    String food = myScan.nextLine().toLowerCase();                                        
    switch (food) {
       case "b" :
         System.out.println("beans");                                      
         done = true;
         break;
       case "e" :
         System.out.println("eggs");                                       
         done = true;
         break;
       ...
       default :
         System.out.println("error");                                      
     }    
  }    
🌐
Kodejava
kodejava.org › how-do-i-validate-input-when-using-scanner
How do I validate input when using Scanner? - Learn Java by Examples
June 6, 2023 - In the code snippet below if the user does not enter a letter the code will keep asking for a valid letter. It loops until the length of the inputted letters equals to the length of secret word. package org.kodejava.util; import java.util.Scanner; public class ScannerValidateLetter { public static void main(String[] args) { ScannerValidateLetter demo = new ScannerValidateLetter(); demo.validateLetter(); } private void validateLetter() { String secretWord = "Hello"; Scanner scanner = new Scanner(System.in); int length = 0; StringBuilder guess = new StringBuilder(); do { System.out.print("Enter
🌐
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, ...
🌐
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