Re-Prompt User After Invalid Input in Java

Re-prompt user after invalid input in Java

Replace if with while.

BAM, problem solved.

How to re-prompt a user after invalid input?

You could do this with a while loop
For example, let's say we only want to except values between 1 and 12 we could do

for(int i = 0; i< month; i++){
System.out.println("Please enter the rainfall for month " +(i + 1) + ": ");
thisYear[i] = myScanner.nextDouble();
while((thisYear[i] > 12) || (thisYear[i] < 1)) {//error message
System.out.println("ERROR Please enter a valid entry");
System.out.println("");
System.out.println("Please enter the rainfall for month " +(i + 1) + ": ");
thisYear[i] = myScanner.nextDouble();
}
}

This would re prompt the user for an entry if it was outside of that range, you can also add additional parameters using || as logical or

Re-prompt user to input a valid input in java

You can use a do-while loop.

do{
//Some code here

//if block
else { // last else block.
System.out.println("Invalid Membership");
continue; // This will skip the rest of the code and move again to the beginning of the while loop.
}

//More code

break; // If the condition was correct, then you need not worry. This statement will pull out of the loop.
}while(true);

You can modify this to put a do-while loop any where you have such requirement.

This would make your whole code to:

public static void main(String[] args) throws Exception
{

InputStreamReader ui = new InputStreamReader (System.in);
BufferedReader inputReader = new BufferedReader(ui);
String membership, tyreRental,parking;
double x = 0d;
do
{
System.out.println("Select Membership Type: (Gold/Silver/Bronze)");
membership = inputReader.readLine();

if (membership.equals("Gold"))
System.out.println("Gold Membership Selected: £" + (x = 750));
else if (membership.equals("Silver"))
System.out.println("Silver Membership Selected: £" + (x = 450));
else if (membership.equals("Bronze"))
System.out.println("Bronze Membership Selected: £" + (x = 250));
else{
System.out.println("Invalid Membership");
continue;
}
break;
}while(true);

do{
System.out.println("Do you require snow tyre rental? (yes/no)");
tyreRental = inputReader.readLine();

if (tyreRental.equals("yes"))
System.out.println("The total so far with tyre rental: £" + (x = x * 1.1));
else if (tyreRental.equals("no"))
System.out.println("The total so far without tyre rental: £" + x);
else{ System.out.println("Invalid response"); continue;}
break;
}while(true);

do{
System.out.println("Would you like to reserve parking? (yes/no)");
parking = inputReader.readLine();

if (parking.equals("yes"))
System.out.println("Membership total: £" + (x = x * 1.08));
else if (parking.equals("no"))
System.out.println("Membership total: £" + x);
else {System.out.println("Invalid response"); continue;}
break;
}while(true);
}

re-prompt user after invalid input in java (try and catch )

use hasNextDouble() instead of using try/catch exception since you are not explicitly catching InputMismatchException

   while (again) {

// if the next is a double, print the value
if (input.hasNextDouble()) {
base = input.nextDouble();
System.out.println("You entered base: " + base);
again = false;
} else {
// if a double is not found, print "Not valid"
System.out.println("Not valid :" + input.next());
again = true;
}


}
again = true;
while (again) {

// if the next is a double, print the value
if (input.hasNextDouble()) {
height = input.nextDouble();
System.out.println("You entered height: " + height);
again = false;
} else {
// if a double is not found, print "Not valid"
System.out.println("Not valid :" + input.next());
again = true;
}


}
area = (base * height) / 2;

How to ignore user invalid input and re-prompt the same question?

You need to move the try-catch inside the while block. Also when there is a InputMismatchException you have to finish reading the line (because you used Scanner#nextInt instead of Scanner#nextLine) and set a variable (repeatValue) to true. With this variable you can decide whether you need to generate new values or use the previous ones.

See it running here:

public static void main(String[] args) {
int score = 0;
int correct = 0;
int done = 0;
Scanner scan = new Scanner(System.in);
boolean repeatValue = false;
int num1 = 0; // put values outside while in order to re-use them when we need to repeat the same question
int num2 = 0;
while (true) {
try {
// if the user input was incorrect (repeatValue = true), use old the previous values for num1 and num2
num1 = repeatValue ? num1 : (int) (Math.random() * 20);
num2 = repeatValue ? num2 : (int) ((Math.random() * 20) + 1);
System.out.printf("%d %% %d = ?\n", num1, num2);
repeatValue = false; // restore flag state
if (scan.hasNext("q"))
break;
if (scan.nextInt() == (num1 % num2)) {
score += 20;
done += 1;
correct += 1;
System.out.println(
"Correct answer,current score :" + score + ",performance: " + correct + "/" + done);
} else {
done += 1;
System.out.println(
"Incorrect answer, Current score:" + score + ", performance: " + correct + "/" + done);
}
} catch (InputMismatchException e) {
System.out.println("invalid input");
scan.next();
repeatValue = true; // flag set to use the same values as before
}
}
System.out.println("Finish");
}

How to reprompt user to put a valid input when user inputs a String (Java)

According to the documentation for Scanner.nextDouble():

InputMismatchException - if the next token does not match the Float regular expression, or is out of range

This means that if the user types in non-numeric characters, nextDouble() will throw this exception.

To allow your program to continue, you need to catch the exception and print out an error message. You can do this with a try...catch statement. I won't get into the details here since there are a lot of resources already available about how to do this.

Alternatively, you can use Scanner.hasNextDouble() to check for a double value first.

The links I gave are all from the official Java API documentation from Oracle. I strongly encourage you to familiarize yourself with these docs. They explain all of the detail you need for each standard Java class.

how do i prompt a user to re enter their input value, if the value is invalid?

System.out.print("Enter the number of cookies you'd like to make:");
int number = input.nextInt();

while(number<=0) //As long as number is zero or less, repeat prompting
{
System.out.println("Please enter a valid number:");
number = input.nextInt();
}

This is about data validation. It can be done with a do-while loop or a while loop. You can read up on topics of using loops.

Remarks on your codes:
You shouldn't declare number twice. That is doing int number more than once in your above codes (which is within same scope).



Related Topics



Leave a reply



Submit