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
You should compare with String equals
while (!loopChoice.equals("Y") && !loopChoice.equals("N"))
Also, replace the or operator with and operator
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 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;
}
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!
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);
}
You are looking for a while loop, something like this.
I use a do ... while to execute the line at least once.
The methods check the value and print a message if this is not correct. Return false will prevent the code to exit the loop and read again.
{
// Creating a new keyboard input
Scanner scanner = new Scanner(System.in);
int room;
do {
// Displaying a message on the screen
System.out.println("What room are you in? ");
room = scanner.nextInt();
} while( !isValid(room) );
... //if else or switch
}
private boolean isValid(int room){
if(room > 4 || room < 1){
System.out.println("Try again ;)" );
return false;
} else return true;
}
This is a quick code note even test.
while (true) {
int room = scanner.nextInt();
if(room < 1 || room > 4) {
System.out.println("Wrong room number, please enter the room number.");
continue;
}
break;
}
if (room == 1)
roomOne();
else if (room == 2)
roomTwo();
else if (room == 3)
roomThree();
else if (room == 4)
roomFour();
Hope it helps, nevertheless you should read a little more about loops.