简体   繁体   English

Do-while循环不等待用户输入?

[英]Do-while loop not waiting for user input?

I'm sure this is something simple that I just can't spot, I have a do while loop prompting the user for an array size, which will be used for the rest of the program. 我确信这是一个简单的东西,我无法发现,我有一个while循环提示用户输入数组大小,这将用于程序的其余部分。 If the user enters the right input, the program continues and works fine, but if the user enters the wrong input... 如果用户输入正确的输入,程序继续并正常工作,但如果用户输入错误的输入...

public static void main(String[] args)
{
  // user enters up to 20 double values, stored in an array, user should enter 99999 to quit entering numbers. If user has not entered any numbers yet
  // display an error message, otherwise, display each entered value and it's distance from the average

  Scanner keyboard = new Scanner(System.in);
  int arraySize = 0;
  boolean isValid = false;

  do
  {
     isValid = true;
     arraySize = 0; // reset these values at start of each loop.

     System.out.println("Enter an array size.");
     try {
        arraySize = keyboard.nextInt();
     }
     catch(NegativeArraySizeException mistake) {
        System.out.println("Do not enter a negative number for the arrays size.");
        System.out.println();
        isValid = false;
     }
     catch(InputMismatchException mistake) {
        System.out.println("Make sure to enter a valid number.");
        System.out.println();
        isValid = false;
     }
  } while (isValid == false);

If the user enters an invalid input, such as "red", the catch block kicks in and prints "Make sure to enter a valid number." 如果用户输入无效输入,例如“红色”,则捕获块将启动并打印“确保输入有效数字”。 and "Enter an array size." 和“输入数组大小。” over and over without giving the user a chance to actually enter any input. 一遍又一遍,不给用户实际输入任何输入的机会。 I figured resetting the arraySize variable would fix it, but it doesn't. 我想重置arraySize变量会修复它,但事实并非如此。 I guess the keyboard buffer has stuff in it, but no combination of empty printlns has worked so far. 我猜键盘缓冲区中有东西,但到目前为止还没有空printlns的组合。

I've heard that Exceptions shouldn't be used to validate user input. 我听说不应该使用Exceptions来验证用户输入。 Why is that? 这是为什么?

Regardless, it's not relevant to this question, as it is an exercise in Exception handling. 无论如何,它与此问题无关,因为它是异常处理中的练习。

Without using isValid boolean variable and make simple code for input. 不使用isValid布尔变量并为输入创建简单代码。

int arraySize = 0;
do {
    System.out.println("Enter a valid array size.");
    try {
        arraySize = Integer.valueOf(keyboard.nextLine());
        if (arraySize < 0) throw new NegativeArraySizeException();// for negative arry size
        break;// loop break when got a valid input
    } catch (Exception mistake) {
        System.err.println("Invalid input: " + mistake);
    }
} while (true);

You can add a keyboard.nextLine(); 你可以添加一个keyboard.nextLine(); in the event of exception and it should resolve the issue. 如果发生异常,它应该解决问题。

 try {
    arraySize = keyboard.nextInt();
 }
 catch(NegativeArraySizeException mistake) {
    System.out.println("Do not enter a negative number for the arrays size.");
    System.out.println();
    isValid = false;
    keyboard.nextLine();
 }
 catch(Exception mistake) {
    System.out.println("Make sure to enter a valid number.");
    System.out.println();
    isValid = false;
    keyboard.nextLine();
   }

Please see if this fix works for you. 请查看此修复程序是否适合您。 Scanner has a problem when you are trying to get the string from nextInt function. 当您尝试从nextInt函数获取字符串时,扫描程序有问题。 In this I have fetched the string and parsed to Integer and then handled the Number format exception 在这里我已经获取了字符串并解析为Integer,然后处理了数字格式异常

public static void main(String[] args) {
    // user enters up to 20 double values, stored in an array, user should enter 99999 to quit entering numbers. If user has not entered any numbers yet
    // display an error message, otherwise, display each entered value and it's distance from the average

    Scanner keyboard = new Scanner(System.in);
    int arraySize = 0;
    boolean isValid = false;

    do {
        isValid = true;
        arraySize = 0; // reset these values at start of each loop.

        System.out.println("Enter an array size.");
        try {
            arraySize = Integer.parseInt(keyboard.next());
        } catch (NegativeArraySizeException mistake) {
            System.out.println("Do not enter a negative number for the arrays size.");
            System.out.println();
            isValid = false;
        } catch (InputMismatchException mistake) {
            System.out.println("Make sure to enter a valid number.");
            System.out.println();
            isValid = false;
        } catch (NumberFormatException nfe) {
            System.out.println("Make sure to enter a valid number.");
            System.out.println();
            isValid = false;
        }

    } while (isValid == false);
}

mmuzahid is almost there. mmuzahid几乎就在那里。 But I added a way of checking negative number as well. 但我还添加了一种检查负数的方法。 Try this 尝试这个

    Scanner keyboard = new Scanner(System.in);
    int arraySize = 0;
    boolean isValid = false;
    do {
        System.out.println("Enter a valid array size.");
        try {
            arraySize = Integer.valueOf(keyboard.nextLine());

            if (arraySize < 0) {
                System.out.println("Make sure to enter a valid positive number.");
            } else {
                break;
            }
        } catch (Exception mistake) {
            System.out.println("Make sure to enter a valid number. Error:" + mistake);
        }
    } while (true);

Use keyboard.nextLine() and NumberFormatException 使用keyboard.nextLine()NumberFormatException

do {
            // more code
            try {
                arraySize = Integer.valueOf((keyboard.nextLine()));
            } catch (NegativeArraySizeException mistake) {
                // more code
                isValid = false;
            } catch (InputMismatchException mistake) {
                // more code
                isValid = false;
            } catch (NumberFormatException mistake) {
                // more code
                isValid = false;
            }
} while (isValid == false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用do-while循环检查Java中用户的输入 - Using a do-while loop to check a User's input in Java Java - 通过用户输入退出 do-while 循环 - Java - get out of the do-while loop with an input of user 如何使用do-while循环再次检查用户输入? - How to use do-while loop to check user input again? 使用do-while循环将用户输入添加到ArrayList - Adding user input to ArrayList using do-while loop 如何使用do-while循环来捕获用户? - How to trap user with do-while loop? 用户输入时执行Do-While循环-检查输入是否为空或int(java) - Do-While loop on user input - check if input is not empty or int (java) Do-While 循环在输入用户输入时显示很多错误(Java -OSGi Equinox in Eclipse EE - Do-While loop is showing a lot of error while entering user input (Java -OSGi Equinox in Eclipse EE Java:尝试通过do-while限制用户输入时,在while循环中进行无限循环 - Java: Infinite looping within while loop when trying to limit user input with do-while Java如何使用用户的布尔输入来结束do-while循环? - Java how to end a do-while loop using boolean input from user? 在 do-while 循环中尝试/捕获以检查用户输入(数组) - 错误的 boolean 初始化和 position - Try / catch in a do-while loop to check user input (array) - wrong boolean initialization and position
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM