简体   繁体   English

当用户输入错误的字符或无效的输入数据时,如何显示“打印”错误?

[英]How to display a “print” error when the user enters wrong character or invalid input data?

I want to know if there is an easy way to display a error for a wrong character or invalid input data. 我想知道是否有一种简单的方法来显示错误字符或无效输入数据的错误。

public static void main(String[] args) {

    // Step 1: Create new Scanner object.
    Scanner input = new Scanner(System.in);         

    // Step 2: Prompt the user to enter today's day.
    System.out.print("Enter today’s day as an Integer (0-6): ");
    int Today = input.nextInt();

    // Step 3: Prompt the user to enter the number of days elapsed since today.
    System.out.print("Enter the number of days elapsed since today as an Integer: ");
    int DaysElapsed= input.nextInt();

    // Step 4: Compute the future day.
    int FutureDay = (Today + DaysElapsed) % 7;

    // Step 5: Printing the results.
        // Step 5.1: Today's day result depending the case.
        System.out.print("Today is ");
            // Step 5.2: Future day result depending the case.
        System.out.print(" and the future day is ");

Since you are only expecting 'int' here from the scanner.nextInt() It will throw an InputMismatchException exception. 因为你只是期望来自InputMismatchException scanner.nextInt() 'int'它将抛出一个InputMismatchException异常。 So you can easily validate your input for int here like this - 因此,您可以像这样轻松验证int的输入 -

try {
   int Today = input.nextInt();
   int DaysElapsed= input.nextInt();
} catch (InputMismatchException){
   System.err.println("Input is not an integer");
}   

Scanner.nextInt() also throws NoSuchElementException and IllegalStateException exceptions Moreover you can validate whetehr an input date is valid by using conditions ( today>=1 && today=<31 ) Scanner.nextInt()也抛出NoSuchElementExceptionIllegalStateException异常此外,您可以通过使用条件验证输入日期是否有效( today>=1 && today=<31

With nextInt() you already filter the allowed values to integers. 使用nextInt(),您已经将允许的值过滤为整数。 But if you want the user to enter values in a limited range you could use something like this: 但是,如果您希望用户输入有限范围内的值,您可以使用以下内容:

    int Today = 0;

    if (input.hasNextInt()) {
        if (input.nextInt() < 32 && input.nextInt() > 0) { //should be between 0-32

            Today = input.nextInt();

        } else {

            throw new Exception("Number must be between 0-32");
        }
    }

Edit: 编辑:

If you want to continue on error: 如果您想继续出错:

    int Today = 0;
    if(input.hasNextInt()) {

        Today = input.nextInt();
        while (!(Today > 0 && Today < 32)){

            System.out.println("Number must be between 0-32");
            Today = input.nextInt();
        }
    }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM