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");
}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
Looping Until the Value Passes - Java
Videos
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));
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);
}
}
In your final code example in the class called CalTest where you assign valX = input.nextDouble(); you could a call recursive method that handles the exception until the input is what you want. Something like this:
private static double getNextDouble(Scanner input) {
try {
return input.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Value X must be a number: ");
input.next();
return getNextDouble(input);
}
}
You'll replace valX = input.nextDouble(); with valX = getNextDouble(input);.
You can tidy this up and make it work for your other potential error cases, perhaps creating a parameter for the output message and passing it in as an argument.
public static void main(String[] args) {
double valX=0,valY=0;
char operator='0';//dummy default
Scanner input = new Scanner(System.in);
System.out.println("Calculator Activated.");
Double dX = null;
do
{
System.out.print("Value X: ");
dX = getDouble(input.next());
}while (dX==null);
{
valX = dX;
}
Character op = null;
do
{
System.out.print("Operator: ");
op = getOperator(input.next());
}while (op==null);
{
operator=op;
}
Double dY = null;
do
{
System.out.print("Value Y: ");
dY = getDouble(input.next());
}while (dY==null);
{
valY = dY;
}
System.out.println("Done: "+ valX + " "+operator + " " +valY);
}
static Double getDouble(String input) {
Double d = null;
try {
d = new Double(input);
}catch(NumberFormatException ex){
}
return d;
}
static Character getOperator(String input) {
Character c = null;
if("+".equals(input) || "-".equals(input) || "*".equals(input) || "/".equals(input)){
c = input.charAt(0);
}
return c;
}
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