首页 > 解决方案 > 如何确保用户在输入无效内容后可以再次输入?

问题描述

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 以外的任何内容是否会要求再试一次,但我永远无法让它工作。有小费吗?

标签: java

解决方案


执行以下操作:

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命名。

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


推荐阅读