问题
I'm writing this program in java where I need to re-prompt the user after an invalid input. I came to a solution only to discover that if the user enters another invalid input after the re-prompt then it continues. Can someone please show me a better solution to this? I'll show you what I had anyway:
System.out.println("What is your age?\n");
age = userInput.nextInt();
if((age > 120) || (age < 1)) {//error message
System.out.println("ERROR Please enter a valid age");
System.out.println("");
System.out.println("What is your age?\n");
age = userInput.nextInt();
}//end if
if the user entered an invalid input after they were prompted again, the program would just continue, how can I overcome this?
回答1:
Replace if
with while
.
BAM, problem solved.
回答2:
Use a while
loop.
while (true) {
System.out.println("What is your age?\n");
age = userInput.nextInt();
if ((age > 120) || (age < 1))
System.out.println("ERROR Please enter a valid age\n");
else
break;
}
回答3:
You could put it in to a while loop so that it keeps looping until the conditions are met --
System.out.println("What is your age?\n");
age = userInput.nextInt();
while((age > 120) || (age < 1)) {//error message
System.out.println("ERROR Please enter a valid age");
System.out.println("");
System.out.println("What is your age?\n");
age = userInput.nextInt();
}//end if
回答4:
use do-while:
boolean valid;
do {
System.out.println("What is your age?\n");
age = userInput.nextInt();
valid = age > 1 && age < 120;
if (!valid) {
System.out.println("ERROR Please enter a valid age");
}
}while (!valid);
回答5:
What about this
---->One time check - is your input is empty or just pressed the spacebar
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a string: ");
String input = scnr.nextLine();
boolean isEmpty = input == null || input.trim().length() == 0;
if (isEmpty){
System.out.println("Enter a string again: ");
input = scnr.nextLine();
}
------> Multiple time check- is your input is empty or just pressed the spacebar
Scanner scnr = new Scanner(System.in);
do {
System.out.println("Enter a string: ");
input = scnr.nextLine();
}
while (input == null || input.trim().length() == 0);
Important: Don't forget that input should be static string in this case.
static String input="";
回答6:
// Using do-while loop, this problem can be tackled.
do {
System.out.println("Enter a pin: ");
pin = sc.nextInt();
} while (pin != 12345);
System.out.println("Welcome to program");
来源:https://stackoverflow.com/questions/18721884/re-prompt-user-after-invalid-input-in-java