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 ?
March 20, 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 - 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.
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.
🌐
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 ...
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);

    }
}
🌐
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 19, 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
🌐
Reddit
reddit.com › r/learnjava › use for loop to get user input and keep prompting for input if the wrong number was entered.
r/learnjava on Reddit: Use for loop to get user input and keep prompting for input if the wrong number was entered.
June 29, 2022 -
        Scanner user_in= new Scanner(System.in);
	System.out.print("Enter an integer between 1-10 : ");
	int n = user_in.nextInt();
			
	for(int i=0; i<1; i++) {
		while(true || !user_in.hasNext()) {
			if(n>=0 && n<=10) {
				System.out.println("You entered : " + n);
				break;
                         }
			else {
				System.out.println("Try again!");
				user_in.next();
                         }
					
		 }			
	 }

So I've trying now to use a for loop to get the user input and keep prompting an input if they enter a number outside the range 1-10. This has been my attempt so far and I keep on failing no matter what I change. Thank you for the help!

Top answer
1 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2 of 4
1
I feel like a while loop would be a better fit for this situation
🌐
Coderanch
coderanch.com › t › 503101 › java › Read-input-user-input-valid
Read input from user until an input is valid (Beginning Java forum at Coderanch)
July 16, 2010 - In this method, include try, catch, and finally, and if invalid inputs, give warning to the user from your catch method, and eventually you'll come to the finally block, so in that block, call the method again, and Check for END(some thing to end the program) input from the user, and if he ...