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

Java 如何确保用户在输入无效内容后可以再次输入?,java,Java,上面的代码有0个错误。但是,我希望代码只允许正整数,如果用户要输入负整数(-20)或字母(abc),那么程序将要求他们重试。我尝试使用If-else语句来说明除了数字>0之外的任何内容是否会要求重试,但我无法使其工作。有什么提示吗?要做到这一点,您需要一个do-while循环,每次检查输入是否有效,循环中还需要一个try-catch块,以便在扫描仪引发异常时,您可以捕获它并要求用户输入正数 此外,您还需要在最后关闭扫描仪 import java.util.Scanner; class recu

上面的代码有0个错误。但是,我希望代码只允许正整数,如果用户要输入负整数(-20)或字母(abc),那么程序将要求他们重试。我尝试使用If-else语句来说明除了数字>0之外的任何内容是否会要求重试,但我无法使其工作。有什么提示吗?

要做到这一点,您需要一个do-while循环,每次检查输入是否有效,循环中还需要一个try-catch块,以便在扫描仪引发异常时,您可以捕获它并要求用户输入正数

此外,您还需要在最后关闭扫描仪

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;
    }
}
import java.util.Scanner;
类递归2{
公共静态void main(字符串参数[]){
扫描仪输入1=新扫描仪(System.in);
扫描仪=新的扫描仪(System.in);
char cont='y';
而(cont=='y'){
System.out.println(“输入编号:”);
int num=-1;//默认为负值,因此无效
do{//do while使其至少运行一次
试一试{
num=scanner.nextInt();
}catch(InputMismatchException e){//当它不是int时,再次循环
System.out.println(“请输入有效输入”);
}

而(num使用此方法验证输入

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;

 }
 }
然后从代码中调用此方法

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.");
    } 
}
您也可以在项目中的任何位置使用此方法。

按以下步骤操作:

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);
 }
运行示例:

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;
    }
}
注意事项:

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;
    }
}
  • 在这种情况下,使用
    do…while
    更合适。这并不意味着不能使用
    while
    循环来完成,但是
    do…while
    使它更容易理解
  • scanner.nextLine().toLowerCase().charAt(0)
    y
    进行比较,以便程序可以继续执行
    y
    y
  • \\d+
    用于限制字符串仅与数字匹配,而不与其他内容匹配,即只允许输入
  • Integer::parseInt
    用于将整数字符串转换为
    int
  • 您不需要两个
    Scanner
    实例
  • 例如,按照命名约定,应将
    类递归2
    命名为
    类递归2

  • 如果有任何疑问/问题,请随时发表评论。

    您需要
    而不是
    如果
    。与if不同,if最多执行一次,而while会重复执行,直到条件返回false为止(例如,重复请求输入,直到输入变为有效)如果您创建一个方法来输入下一个正整数,这可能是最简单的。您将有一个循环,该循环将一直工作,直到您获得有效的输入。对不起,但是如果您确实获得了一个正整数,该怎么办?