在Java中,调用后输入函数得到错误的值?

在Java中,调用后输入函数得到错误的值?,java,Java,我有一个问题,当我为数组2d输入值时,值是有效的,所有操作都完成了,但当我为totalRow或totalColumn变量输入错误的值时,我的输入函数强制我输入双精度值,并在第二个值中获取值。 这是我的代码: public static void input() { Scanner sc = new Scanner(System.in); try { System.out.println("Input total totalRow: "); tota

我有一个问题,当我为数组2d输入值时,值是有效的,所有操作都完成了,但当我为totalRow或totalColumn变量输入错误的值时,我的输入函数强制我输入双精度值,并在第二个值中获取值。 这是我的代码:

public static void input() {
    Scanner sc = new Scanner(System.in);
    try {
        System.out.println("Input total totalRow: ");
        totalRow = sc.nextInt();
        // verify value input must be a positive integer and greater than zero
        if (totalRow <= 0) {
            System.out.println("Input value must be a positive integer and greater than zero!");
            input();
        }

        System.out.println("Input total totalColumn: ");
        totalColumn = sc.nextInt();
        // verify value input must be a positive integer and greater than zero
        if (totalRow <= 0) {
            System.out.println("Input value must be a positive integer and greater than zero!");
            input();
        }

        // check case array must be square array
        if (totalRow != totalColumn) {
            System.out.println("Array must be square!");
            input();
        }
    } catch (InputMismatchException e) {
        // print message when user input other than integer
        System.out.println("Please input an integer!");
        input();
    }

    // initialize array with totalRow and totalColumn
    array = new char[totalRow][totalColumn];

    // input value for array
    for (int i = 0; i < totalRow; i++) {
        for (int j = 0; j < totalColumn; j++) {
            array[i][j] = sc.next().charAt(0);
        }
    }
}
公共静态无效输入(){
扫描仪sc=新的扫描仪(System.in);
试一试{
System.out.println(“输入总计行:”);
totalRow=sc.nextInt();
//验证值输入必须为正整数且大于零

如果(totalRow这里有两件事使代码失败:


  • 打字错误:您正在检查
    totalRow这里有两件事使您的代码失败:


  • 输入错误:您正在检查
    totalRow递归算法有问题。即使它对正确的输入有效,对于错误的输入,它也会重复要求值。因为当您犯任何错误input()函数将从头开始。因此,如果您想更好地使用递归,请对输入总计列()和输入总计行()使用单独的函数。
    还有一个复制粘贴错误。您正在检查totalColumn递归算法有问题。即使它适用于正确的输入,对于错误的输入,它也会重复请求值。因为当您犯任何错误input()函数将从头开始。因此,如果您想更好地使用递归,请对输入总计列()和输入总计行()使用单独的函数。
    还有一个复制粘贴错误。您正在检查totalcolumn您可能不希望对输入使用递归重复您可能不希望对输入使用递归重复
    if (totalRow <= 0) {
            System.out.println("Input value must be a positive integer and greater than zero!");
            //input();
            }
    
            System.out.println("Input total totalColumn: ");
            totalColumn = sc.nextInt();
            sc.nextLine();
            // verify value input must be a positive integer and greater than
            // zero
            if (totalColumn <= 0) {
            System.out.println("......
    
        for (int j = 0; j < totalColumn; j++) {
    
            array[i][j] = sc.next().charAt(0);
    
        }
    }