java - 当用户输入错误字符或无效输入数据时如何显示 "print"错误?

标签 java eclipse

我想知道是否有一种简单的方法来显示错误字符或无效输入数据的错误。

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 ");

最佳答案

因为您只期望 scanner.nextInt() 中的“int”它将抛出 InputMismatchException异常(exception)。因此您可以轻松验证 int 的输入像这样 -

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

Scanner.nextInt()还抛出NoSuchElementExceptionIllegalStateException异常(exception)情况 此外,您可以使用条件( today>=1 && today=<31 )验证输入日期是否有效

关于java - 当用户输入错误字符或无效输入数据时如何显示 "print"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56119219/

相关文章:

java - Eclipse 快速修复不完整

java - 第二次无法从用户处获取字符串输入的输入

java - 使用测试类来查看两个整数值是否适合参数

java - 使用 quaqua LAF 在 Swing Mac OSX 应用程序上获取未保存的点

java - Rest服务如何处理父子关系

java - org.eclipse.ui.PlatformUI 类在哪里?

java - 尝试使用 JDBC 测试 MySQL 数据库中是否存在特定表时出错

java - JOptionPane 更大

eclipse - Nodejs 无法与 Intellij Idea 一起使用

android - 将 Eclipse 连接到不同机器上的 Android 模拟器