Use a while loop above input line as:

 while(true)

And, use if condition to break.

if(year == 0)
    break;

Also, condition for leap year is wrong in your code. It should be:

if((year % 100 == 0 && year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
    //its a leap year
else
    //its not

PS: As in comments, I'll give a complete code:

import java.util.*;

public class Task10 {

public static void main(String[] args) {
    System.out.println("Enter a year to check if it is a leap year");
    while(true){
    Scanner input = new Scanner(System.in);
        int year = input.nextInt();
        if(year == 0)
            break;
        if((year % 100 == 0 && year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
            System.out.println(year + " is a leap year");
        else
            System.out.println(year + " is not a leap year");
    }
}

}
Answer from vish4071 on Stack Overflow
๐ŸŒ
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 - As the code above shows, the readUserInput method reads user input from System.in and stores the data in the userData List. Once we receive โ€œbyeโ€ from the user, we break the infinite while loop.
Discussions

Use for loop to get user input and keep prompting for input if the wrong number was entered.
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. More on reddit.com
๐ŸŒ r/learnjava
9
2
June 29, 2022
Pausing a while loop to get user input, help

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

  • 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.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

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: 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.

More on reddit.com
๐ŸŒ r/javahelp
6
4
November 1, 2021
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 end a while Loop via user input - Stack Overflow
You just need to set repeat to true or false based on user input. So in the end, compare input with yes or no. Something like this would work for you : if ("yes".equals(input)) repeat = true; // This would continue the loop else repeat = false; // This would break the infinite while loop 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 - JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility ... Here's a more updated version of the code: where the string for letterInput can only be accepted if its 2 characters long, and the string cannot contain a space because the characters that are accepted have to be two letters from a-f or either character being a blank space. Also, the code now only runs and will continue to run on a loop when the boolean of runProgram is true. If the user input for [i]userName[/u] is 'q', runProgram will render false, thus preventing the code from running and stopping the loop altogether.
๐ŸŒ
Quora
quora.com โ€บ How-can-you-do-a-do-while-loops-in-Java-with-user-input-and-statement
How to do a do while loops in Java with user input and statement - Quora
... A doโ€‘while loop in Java executes ... combined with user input (Scanner), itโ€™s commonly used to prompt the user and continue until they choose to stop or enter a sentinel value....
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_while_loop.asp
Java While Loop
In the next chapter, you will learn about the do while loop, which always runs the code at least once before checking the condition. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com ยท If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com ยท HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
๐ŸŒ
Programming Simplified
programmingsimplified.com โ€บ java โ€บ tutorial โ€บ java-while-loop
Java while loop | Programming Simplified
We test a user input and if it's zero then we use "break" to exit or come out of the loop. ... class BreakWhileLoop { public static void main(String[] args) { int n; Scanner input = new Scanner(System.in); while (true) { // Condition in while loop is always true here System.out.println("Input ...
๐ŸŒ
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.
Find elsewhere
๐ŸŒ
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
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ do-while-loop
Java while and do...while Loop
In the above program, we have used the Scanner class to take input from the user. Here, nextInt() takes integer input from the user. The while loop continues until the user enters a negative number.
๐ŸŒ
Linus Tech Tips
linustechtips.com โ€บ software โ€บ programming
How can I do a while loop with user input? (Java) - Programming - Linus Tech Tips
January 4, 2018 - Hi everyone, the problem I'm having is specifically with the while loop. I learned C++ before this, and that is why the loop is written that way Example: while (cin >> input) {...} I know that the way I'm trying to use the scanner doesn't work, because it requires the user to input twice, b...
๐ŸŒ
Quora
quora.com โ€บ How-do-I-do-a-while-loop-in-a-user-input-array-in-Java
How to do a while loop in a user input array in Java - Quora
Answer: [code]public static void main(String[] args) { Scanner scan = new Scanner(System.in); int i = 0; int n = 0; int[] myArray = new int[10]; System.out.printf("enter a value>>"); while (scan.nextInt() > 0) { for (i = 0; i > 0; i++) { myArray[i] = sc...
๐ŸŒ
BeginwithJava
beginwithjava.com โ€บ java โ€บ loops โ€บ do-while-loop.html
Do While Loop in Java
Scanner console = new Scanner(System.in); // Get random number between 1 to 100. num = (int) (Math.random() * 100) + 1; do { System.out.print("Enter an integer between 1 to 100: "); guess = console.nextInt(); if (guess == num) { System.out.println("You guessed the correct number."); } else if (guess < num) { System.out.println( "Your guess is lower than the number.\nGuess again!"); } else { System.out.println( "Your guess is higher than the number.\nGuess again!"); } } while (guess != num); } }
๐ŸŒ
GitHub
gist.github.com โ€บ 4178829
Created this to figure out accepting user input in a while loop ยท GitHub
Created this to figure out accepting user input in a while loop - whileLoop.java
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 684625 โ€บ java โ€บ loop-user-input
While loop and user input (Beginning Java forum at Coderanch)
September 12, 2017 - Carey Brown wrote:You'll want to replace your a-- with edd.nextInt(). Every time through the loop you'll want to get another int. Also, variable names should begin with a lower case character, so it should be edd and not Edd. Alright but if i want to now use a text and number, and I want to print the text much as the number specifies, how do I do that? using While Thanks for your help! Hope you dont mind these noob questions. ... Mixing input as a number and as text potentially exposes you to one of the Scanner's gotchas.
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ pausing a while loop to get user input, help
r/javahelp on Reddit: Pausing a while loop to get user input, help
November 1, 2021 -

Hello reddit! Here is my code for my assignment for my compsci class in college. I am a beginner but have the task of making a user-input binary string that updates after every user input. I have nested the program in a while loop so it reprompts the user every time to get a new input for the user. However, it infinitely uses the user's first input each time, with no way to pause the loop to wait for the user's input again. Is there a fix for this? Any help is greatly appreciated. Thank you all for your time! :)

import java.util.Scanner;

public class Program05a {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	Scanner stdIn = new Scanner (System.in);
	
	String bitString = "";
	int resultSoFar = 0;
	int userInput = 3;
	while (userInput != 2)
	{
		System.out.println("0 -> Shift Left, Add 0");
		System.out.println("0 -> Shift Left, Add 1");
		System.out.println("2 -> Exit, Evaluate");
		while ((userInput != 1) && (userInput != 2) && (userInput != 0))
		{
			System.out.print("Choose an operator from the menu above : ");
			userInput = stdIn.nextInt();
		}
		if (userInput != 2)
		{
			if (userInput == 0)
			{
				bitString = bitString + "0";
				System.out.println(bitString);
				resultSoFar = 2*resultSoFar + 0;
			}
			else if (userInput == 1)
			{
				bitString = bitString + "1";
				System.out.println(bitString);
				resultSoFar = 2*resultSoFar + 1;
			}
			
		}
	}
	System.out.println("\nThe value of the bit is: " + resultSoFar);
	
	stdIn.close();

}

}

Top answer
1 of 2
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

  • 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.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

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: 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 2
1

Step through your code line by line (manually don't actually run it) and see how userInput changes as you loop though the program.

Especially look at this line:

userInput = stdIn.nextInt();

As it's the only line that changes the value of userInput.

Example:

for(int i = 0; i < 4; i++) {
    // i == 0, 1, 2, 3
    if(i % 2 == 0) { // true for 0 and 2
        print(i); // prints 02
    }
}
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ java-how-to-control-program-flow-using-while-loop-in-java-413962
How to control program flow using while loop in Java | LabEx
Inside the loop, the code prompts the user to enter a positive integer, and if the input is valid and positive, the loop is terminated using the break statement. If the input is invalid, an error message is displayed, and the loop continues.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Java Do While Loop Example Where User Prompts to Start Program Over - Appficial - YouTube
More videos coming soon, please SUBSCRIBE!A do-while loop is a post-test loop that executes its body of code at least once, and then repeats while the loop's...
Published ย  October 7, 2017
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 697352 โ€บ java โ€บ Loop-Scanner-Class
Using While Loop and Scanner Class [Solved] (Beginning Java forum at Coderanch)
July 31, 2018 - I have been set the task to compile some code which uses the While Loop to ask the user to input a non-negative integer and give an error message if a negative value is entered. I don't know what I am doing wrong here, but would I be right in thinking the fault lies somewhere with the square ...