如何确保用户在输入无效内容后可以再次输入?

huangapple go评论85阅读模式
英文:

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 = &#39;y&#39;;
while (cont == &#39;y&#39;) {
System.out.println(&quot;Enter the number:&quot;);
int num = scanner.nextInt();
int factorial = fact(num);
System.out.println(&quot;Factorial of entered number is: &quot; + factorial);
System.out.println(&quot;Do you want to loop again?&quot;);
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(&quot;Enter the number:&quot;);
int num = scanner.nextInt();
if(num &gt; 0) {
return num;
}
System.out.println(&quot;Input must be greater than zero. Please try again.&quot;);
} 
}

Then call this method from your code.

while (cont == &#39;y&#39;) {
int num = validInput();
int factorial = fact(num);
System.out.println(&quot;Factorial of entered number is: &quot; + factorial);
System.out.println(&quot;Do you want to loop again?&quot;);
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!

注:

  1. 在这种情况下,使用do...while更为合适。这并不意味着不能使用while循环,但是do...while使得代码更加易于理解。
  2. scanner.nextLine().toLowerCase().charAt(0)y进行比较,以便程序可以同时继续处理Yy
  3. 使用\\d+来限制字符串仅匹配数字,不允许其他内容,即只允许整数。
  4. 使用Integer::parseInt将整数字符串转换为int
  5. 您不需要两个Scanner实例。
  6. 遵循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 = &#39;y&#39;;
int num;
boolean valid;
String strNum;
do {
valid = false;
System.out.print(&quot;Enter the number: &quot;);
strNum = scanner.nextLine();
if (strNum.matches(&quot;\\d+&quot;)) {
int factorial = fact(Integer.parseInt(strNum));
System.out.println(&quot;Factorial of entered number is: &quot; + factorial);
System.out.print(&quot;Do you want to loop again?&quot;);
cont = scanner.nextLine().toLowerCase().charAt(0);
} else {
System.out.println(&quot;Invalid entry. Please try a positive integer.&quot;);
}
} while (cont == &#39;y&#39;);
System.out.println(&quot;Goodbye!&quot;);
}
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:

  1. Use of do...while is more appropriate in this case. It doesn't mean that it can not be done using while loop but do...while makes it more comprehensible.
  2. Compare scanner.nextLine().toLowerCase().charAt(0) with y so that the program can continue for both Y and y.
  3. \\d+ is used to restrict a string matching with only digits and nothing else i.e. it allows only intgers.
  4. Integer::parseInt is used to convert an integer string into int.
  5. You do not need two Scanner instances.
  6. Follow Java naming conventions e.g. class recursion2 should be named as class 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 = &#39;y&#39;;
while (cont == &#39;y&#39;) {
System.out.println(&quot;Enter the number:&quot;);
int num = -1;  //Negative by default so it&#39;s invalid
do {  //Do-while so it gets run at least once
try {
num = scanner.nextInt();
} catch (InputMismatchException e) { //When it&#39;s not an int, loop again
System.out.println(&quot;Please enter a valid input&quot;);
}
while (num &lt;= 0); //Check if positive here
int factorial = fact(num);
System.out.println(&quot;Factorial of entered number is: &quot; + factorial);
System.out.println(&quot;Do you want to loop again?&quot;);
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;
}
}

huangapple
  • 本文由 发表于 2020年4月8日 06:11:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/61090201.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定