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 OverflowHello, 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");
}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");
}
}
}
Use a while loop instead,
while (!guess.equals(secret)) {
if( guess.equals(secret) ) {
System.out.println( "enter" );
} else {
System.out.println( "try again" ); {
System.out.println("Secret word")
guess = input.next();
}
}
Apart from this, the for loop have the following syntax,
for (before, conditionsIsTrue, end)
This means that for you the loop will be like this,
for(int i=0; if(guess.equals(secret)), i++)
Since this condition will never hold for the first loop you will never enter the for loop at all.
You can also use do-while which uses a post test,
do {
System.out.println("Secret word")
guess = input.next();
if( guess.equals(secret) ) {
System.out.println( "enter" );
} else {
System.out.println( "try again" ); {
}
} while (!guess.equals(secret));
java - Loop user input until conditions met - Stack Overflow
java - How to loop through until user inputs a valid integer? - Stack Overflow
java - Unable to loop until valid value is entered - Stack Overflow
Java Wrong Input For Vector Loop Until Correct - Stack Overflow
Videos
Easy with do-while:
Scanner keyboard = new Scanner(System.in);
int startr, endr;
boolean good = false;
do
{
System.out.println("Enter the Starting Number of the Range: ");
startr = keyboard.nextInt();
if(startr % 10 == 0 && startr >= 0)
good = true;
else
System.out.println("Numbers is not divisible by 10");
}
while (!good);
good = false;
do
{
System.out.println("Enter the Ending Number of the Range: ");
endr = keyboard.nextInt();
if(endr % 10 == 0 && endr <= 1000)
good = true;
else
System.out.println("Numbers is not divisible by 10");
}
while (!good);
// do stuff
You need to use a while, something like:
while conditionsMet is false
// gather input and verify
if user input valid then
conditionsMet = true;
end loop
should do it.
You are seeing outputs for each input because you call main recursively. If you immediately type a correct int, the flow is this:
main
ask for input -> int
print i (1)
But in your case the input is not an int. This is what happens: you type the first input, it fails. You do not print yet because you first call main again, asking for the next input. Only when you get a correct int you print, and then finish and allow the previous main-execution to finish by printing, which then allows the previous... and so on:
main(args)
ask for input -> a !int
main(args)
ask for input -> d !int
main(args)
ask for input -> 2.0 !int
main(args)
ask for input -> 1 int
print 1 (1)
print 0 (2.0)
print 0 (d)
print 0 (a)
Look at Ravi's answer for a proper way to repeatedly ask for input without using try/catch (which is discouraged).
You could check for integer token in loop
while (!sc.hasNextInt()) // loop until next token is integer
{
// do something or print error
System.out.println(sc.next() +"is not number");
}
i = sc.nextInt();
but here I want to loop until valid value is entered
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:
System.out.println("enter a number");
int a=sc.nextInt();
while(!validateValue(a)){ //so long value is invalid, repeat.
System.out.println("enter a number");
a=sc.nextInt(); //prompt for input
}
System.out.println("valid value");
But if I were you, I will use a do-while loop, so we do not have to prompt for input twice.
do{
System.out.println("enter a number");
a=sc.nextInt();
}while(!validateValue(a));
System.out.println("valid value");
b should be false, until a valid answer has been given:
boolean b=false;
while (!b){
b=m.validateValues(a);
if(b){
System.out.println("valid value");
break;
}
}
Which is the same as:
boolean b=false;
while (!b){
b=m.validateValues(a);
}
System.out.println("valid value");
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);
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);
}
}
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");
}
}
}
You need to do something to keep you input loop running until a stopping condition is encountered (which in your case is that when the user inputs 0)
// First get the scanner object with the input stream
Scanner sc = new Scanner(System.in);
// Just using do-while here for no reason, you can use a simple while(true) as well
do{
int input = sc.nextInt(); // read the next input
if (int == 0) { // check if we need to exit out
// break only if 0 is entered, this means we don't want to run the loop anymore
break;
} else {
// otherwise, do something with the input
}
} while(true); // and keep repeating
That's not how you compare strings in Java.
There is also a logical error in your code, as the string can't be both Y and N at the same time, you have to use && instead of ||. As long as the choice is neither Y or N, you want to continue the loop. If it is any of them, you want to stop. So && is the correct choice here.
To check if two strings are equal, you have to use .equals(obj)
while (!loopChoice.equals("Y") && !loopChoice.equals("N")) {
The reason for this is that == compares object references, and two Strings are most often not the same object reference. (Technically, they can be the same object reference, but that's not something you need to worry about now) To be safe, use .equals to compare Strings.
To avoid a possible NullPointerException in other situations, you can also use:
while (!"Y".equals(loopChoice) && !"N".equals(loopChoice)) {
You should compare with String equals
while (!loopChoice.equals("Y") && !loopChoice.equals("N"))
Also, replace the or operator with and operator
Let's come up with an sample for you so you can follow as your blueprint
first, I chose do while loop because you need to ask this question at least once.
he syntax of a do...while loop is:
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.
Next, you need to see how you can staisfy the boolean_experssion when the input is right, so you can stop looping or if it is wrong, you keep asking the question.
The way that I really like is to use sentinel value because using break keyword really scares me.
In programming, a special value that is used to terminate a loop. The sentinel value typically is chosen so as to not be a legitimate data value that the loop will encounter and attempt to perform with. For example, in a loop algorithm that computes non-negative integers, the value "-1" can be set as the sentinel value as the computation will never encounter that value as a legitimate processing output.
so when the input is right you change the value of i, so you can stop the looping or otherwise, showing the message and asking the question again and again till the use hits the right answer.
Code:
int i = 0;
Scanner input = new Scanner(System.in);
while (i == 0) {
System.out.println("Enter number zero plz");
int result = input.nextInt();
if(result == 0 ){
System.out.println("I entered right number");
i = 1;
} else
System.out.println("you entered the wrong number \nplz try again");
}
output:

Since this is clearly a homework / learning exercise, I won't give you code. You will learn more if you do the actual coding for yourself.
Once you have fixed the problem with the loop nesting ...
There are three problems with this code:
while (!inputValid) {
System.out.print("How many integers? (Enter a positive integer): ");
try {
totalIntegers = input.nextInt();
inputValid = true;
} catch (NumberFormatException e) {
System.out.println("Invalid input!");
}
}
First problem is that you are catching the wrong exception. Read the javadoc.
The second problem is that if nextInt fails (due to a problem parsing the integer) it puts the scanner's input cursor back to where it was before the call. And when you call it again (in the next loop iteration) it will attempt to read same "bad" number again, and again, and again, ...
You have to tell the scanner to skip over the invalid line of input so that it can read the user's next attempt.
The third problem is that you don't check that the number you just read is positive!!
Final hint: consider using while (true) and a conditional break, instead of while (condition). I think it gives a more elegant solution.
@Kick Buttowski's solution deals with the bad input skipping by creating a new Scanner on each loop iteration. Apparently it works ... but I have some doubts1 that you can rely on this always working. IMO a better solution would be to use one Scanner throughout, and use a nextLine() call to read and discard the characters up to and including the end of line.
1 - My main concern is that when you leak a Scanner that it might (in some implementations) close the underlying input stream in a finalizer. If that actually happened, then the application would stop accepting input. The current implementation does not do this, but this is not clearly specified (AFAIK).
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!
You should have an else case:
if(playerValue > 10 && playerValue < 21){
System.out.println("Players Value so far " + playerValue + ", Do you want to draw another card? Y/N");
// input a y or n answer
decision = sob.next();
if(decision.equalsIgnoreCase("Y")){
continue;
}else if(decision.equalsIgnoreCase("N")){
break;
}
else
{
//whatever you want to happen if they don't enter either y or n
}
}
}
Maybe in the else have another loop that says please enter a valid input and keep looping until they give a valid input...
Here is how you can change your code to "insist" on the user to enter a Y or a N:
static void readYesOrNo(Scanner input) {
String str;
while (true) {
str = input.next();
if (str.equalsIgnoreCase("y")) {
return true;
}
if (str.equalsIgnoreCase("n")) {
return false;
}
System.out.println("Please enter Y or N");
}
}
I put this code into a static method so that you could reuse it in other places. Now you can use this method in your code like this:
if(playerValue > 10 && playerValue < 21){
System.out.println("Players Value so far " + playerValue + ", Do you want to draw another card? Y/N");
if (readYesOrNo(sob)) {
continue;
}
break;
}
In general, use break inside a while loop is considered a bad practice. You should have something like this
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
int minimum = 5;
int maximum = 15;
do{
System.out.print("Enter a number between" + " " + minimum + " " + "and" + " " + maximum + ":" );
number = input.nextInt();
if (number < minimum || number > maximum)
System.out.print("Sorry, invalid");
} while (number < minimum || number > maximum);
}
There is a logical error in your code in the placement of your break and scanner input. If you really want to stay true to what you have, I find it much simpler to just add a boolean check instead of using a break. Below you can see I also put final so that way you know, and is a best practice that, that variable should not be altered or tampered with in code. I added a boolean since you wanted to check the do while for false, then we set it to true if it passes the if statement you made.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
boolean check = false;
// Final, because they are constant through-out the program
final int minimum = 5;
final int maximum = 15;
do {
System.out.print("Enter a number between " + minimum + " and " + maximum + ":" );
number = input.nextInt();
if (number >= minimum && number <= maximum)
check = true;
else
System.out.println("Sorry, invalid");
break;
} while (check);
}