[英]How can I make sure the User can input again after entering something invalid?
import java.util.Scanner;
class recursion2 {
public static void main(String args[]) {
Scanner input1 = new Scanner(System.in);
Scanner scanner = new Scanner(System.in);
char cont = 'y';
while (cont == 'y') {
System.out.println("Enter the number:");
int num = scanner.nextInt();
int factorial = fact(num);
System.out.println("Factorial of entered number is: " + factorial);
System.out.println("Do you want to loop again?");
cont = input1.next().charAt(0);
}
}
static int fact(int n) {
int output;
if (n == 1) {
return 1;
}
output = fact(n - 1) * n;
return output;
}
}
The code above has 0 errors.上面的代码有 0 个错误。 However, Id like the code to only allow positive integers and if a user were to enter a negative integer (-20) or letters (abc) then the program would ask them to try again.
但是,我希望代码只允许正整数,如果用户要输入负数 integer (-20) 或字母 (abc),那么程序会要求他们再试一次。 I tried to use an If else statement saying if anything other than numbers > 0 would ask to try again but I could never make it work.
我尝试使用 If else 语句来说明除数字 > 0 以外的任何内容是否会要求再试一次,但我永远无法让它工作。 Any tips?
有小费吗?
Use this method to validate the input.使用此方法验证输入。
public int validInput() {
Scanner scanner = new Scanner(System.in);
while(1) {
// If you wish to end the loop after a certain number of attempts
// use a counter to exit the loop
System.out.println("Enter the number:");
int num = scanner.nextInt();
if(num > 0) {
return num;
}
System.out.println("Input must be greater than zero. Please try again.");
}
}
Then call this method from your code.然后从您的代码中调用此方法。
while (cont == 'y') {
int num = validInput();
int factorial = fact(num);
System.out.println("Factorial of entered number is: " + factorial);
System.out.println("Do you want to loop again?");
cont = input1.next().charAt(0);
}
You can also use this method anywhere in your project.您也可以在项目的任何地方使用此方法。
Do it as follows:执行以下操作:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char cont = 'y';
int num;
boolean valid;
String strNum;
do {
valid = false;
System.out.print("Enter the number: ");
strNum = scanner.nextLine();
if (strNum.matches("\\d+")) {
int factorial = fact(Integer.parseInt(strNum));
System.out.println("Factorial of entered number is: " + factorial);
System.out.print("Do you want to loop again?");
cont = scanner.nextLine().toLowerCase().charAt(0);
} else {
System.out.println("Invalid entry. Please try a positive integer.");
}
} while (cont == 'y');
System.out.println("Goodbye!");
}
static int fact(int n) {
int output;
if (n == 1) {
return 1;
}
output = fact(n - 1) * n;
return output;
}
}
A sample run:示例运行:
Enter the number: a
Invalid entry. Please try a positive integer.
Enter the number: 10.5
Invalid entry. Please try a positive integer.
Enter the number: -5
Invalid entry. Please try a positive integer.
Enter the number: 5
Factorial of entered number is: 120
Do you want to loop again?y
Enter the number: 3
Factorial of entered number is: 6
Do you want to loop again?n
Goodbye!
Notes:笔记:
do...while
is more appropriate in this case.do...while
更合适。 It doesn't mean that it can not be done using while
loop but do...while
makes it more comprehensible.while
循环来完成,而是do...while
使它更易于理解。scanner.nextLine().toLowerCase().charAt(0)
with y
so that the program can continue for both Y
and y
.scanner.nextLine().toLowerCase().charAt(0)
与y
进行比较,以便程序可以继续为Y
和y
运行。\\d+
is used to restrict a string matching with only digits and nothing else ie it allows only intgers. \\d+
用于限制仅与数字匹配的字符串,即它只允许整数。Integer::parseInt
is used to convert an integer string into int
. Integer::parseInt
用于将 integer 字符串转换为int
。Scanner
instances.Scanner
实例。class recursion2
should be named as class Recursion2
as per the naming convention.class recursion2
应根据命名约定命名为class Recursion2
。 Feel free to comment in case of any doubt/issue.如有任何疑问/问题,请随时发表评论。
To do this, you need a do-while loop where you check each time if the input is valid, and also a try-catch block inside the loop so if the Scanner throws an exception, you can catch it and ask the user to enter a positive number.为此,您需要一个 do-while 循环,每次检查输入是否有效,以及循环内的 try-catch 块,因此如果扫描程序抛出异常,您可以捕获它并要求用户输入一个肯定的数字。
Also, you need to close the scanner at the end.此外,您需要在最后关闭扫描仪。
import java.util.Scanner;
class recursion2{
public static void main(String args[]){
Scanner input1 = new Scanner(System.in);
Scanner scanner = new Scanner(System.in);
char cont = 'y';
while (cont == 'y') {
System.out.println("Enter the number:");
int num = -1; //Negative by default so it's invalid
do { //Do-while so it gets run at least once
try {
num = scanner.nextInt();
} catch (InputMismatchException e) { //When it's not an int, loop again
System.out.println("Please enter a valid input");
}
while (num <= 0); //Check if positive here
int factorial = fact(num);
System.out.println("Factorial of entered number is: " + factorial);
System.out.println("Do you want to loop again?");
cont = input1.next().charAt(0);
}
scanner.close();
}
static int fact(int n)
{
int output;
if(n == 1){
return 1;
}
output = fact(n - 1) * n;
return output;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.