java - 如何确保用户在输入无效内容后可以再次输入?
问题描述
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;
}
}
上面的代码有 0 个错误。但是,我希望代码只允许正整数,如果用户要输入负整数 (-20) 或字母 (abc),那么程序会要求他们再试一次。我尝试使用 If else 语句来说明除数字 > 0 以外的任何内容是否会要求再试一次,但我永远无法让它工作。有小费吗?
解决方案
执行以下操作:
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;
}
}
示例运行:
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!
笔记:
- 在这种情况下使用
do...while
更合适。这并不意味着它不能使用while
循环来完成,而是do...while
让它更易于理解。 - 比较
scanner.nextLine().toLowerCase().charAt(0)
,y
以便程序可以继续为Y
和y
。 \\d+
用于限制仅与数字匹配的字符串,即它只允许整数。Integer::parseInt
用于将整数字符串转换为int
.- 您不需要两个
Scanner
实例。 - 遵循Java 命名约定,例如
class recursion2
应该按照命名约定class Recursion2
命名。
如有任何疑问/问题,请随时发表评论。
推荐阅读
- python - 如何将张量转换为 ndarray(内部带有对抗图像的张量)
- javascript - NightmareJS .then 在 .evaluate 完成之前执行
- odoo-10 - 如何在odoo10中为库存用户隐藏表单的创建和编辑按钮以及批次/序列号的树视图
- python - 如何按数字将字符串拆分为列表?
- php - Laravel 随机丢弃会话
- apache-zookeeper - Zookeeper 3.5 和 Curator 4.0:InterProcessMutex release() 没有删除锁路径
- python - kibana 和 pandas 数据框中的记录数不同
- c++ - 为什么我们真的需要特别是 C++ 编程中的指针
- python - 使用数据集 API 从 tensorflow 中的冻结模型进行推断
- android - 库 Glide/PhotoView/ZGallery 之间的冲突