英文:
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;
while (true) {
try {
num = scanner.nextInt();
if (num <= 0) {
System.out.println("Please enter a positive integer:");
continue;
}
break;
} catch (Exception e) {
System.out.println("Invalid input. Please enter a positive integer:");
scanner.next();
}
}
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;
}
}
英文:
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. 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. 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. Any tips?
答案1
得分: 2
使用这个方法来验证输入。
public int validInput() {
Scanner scanner = new Scanner(System.in);
while(true) {
// 如果你希望在一定尝试次数后结束循环
// 可以使用一个计数器来退出循环
System.out.println("输入一个数字:");
int num = scanner.nextInt();
if(num > 0) {
return num;
}
System.out.println("输入必须大于零,请重新尝试。");
}
}
然后从你的代码中调用这个方法。
while (cont == 'y') {
int num = validInput();
int factorial = fact(num);
System.out.println("输入数字的阶乘是:" + factorial);
System.out.println("是否要再次循环?");
cont = input1.next().charAt(0);
}
你也可以在项目的任何地方使用这个方法。
英文:
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.
答案2
得分: 2
按以下步骤进行操作:
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
,根据命名约定。
英文:
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:
- Use of
do...while
is more appropriate in this case. It doesn't mean that it can not be done usingwhile
loop butdo...while
makes it more comprehensible. - Compare
scanner.nextLine().toLowerCase().charAt(0)
withy
so that the program can continue for bothY
andy
. \\d+
is used to restrict a string matching with only digits and nothing else i.e. it allows only intgers.Integer::parseInt
is used to convert an integer string intoint
.- You do not need two
Scanner
instances. - Follow Java naming conventions e.g.
class recursion2
should be named asclass Recursion2
as per the naming convention.
答案3
得分: 1
为了完成这个任务,您需要使用一个do-while循环,每次检查输入是否有效,还需要在循环内部使用try-catch块,以便如果Scanner引发异常,您可以捕获它并要求用户输入一个正数。
此外,您需要在最后关闭扫描器。
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("请输入数字:");
int num = -1; //默认为负数,因此无效
do { //使用do-while确保至少执行一次
try {
num = scanner.nextInt();
} catch (InputMismatchException e) { //当输入不是整数时,重新循环
System.out.println("请您输入有效的输入");
scanner.next(); //清除无效输入
}
} while (num <= 0); //在此处检查是否为正数
int factorial = fact(num);
System.out.println("输入数字的阶乘是:" + factorial);
System.out.println("您想要再次循环吗?");
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;
}
}
英文:
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.
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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论