【问题标题】:What possible exceptions are there if User enters String instead of Int?如果用户输入 String 而不是 Int,会有哪些可能的例外?
【发布时间】:2019-04-01 08:34:49
【问题描述】:

我只是在玩 Java。我试图强制我的程序只接受数字 1 和 2。我相信我已经使用 while 循环成功地做到了这一点(如果我错了,请纠正我)。但是,如果用户输入字符串,我该如何打印错误语句。例如:“abc”。

我的代码:

    while (response != 1 && response != 2) {
        System.out.println("Please enter 1 for Car or 2 for Van: ");
        response = scan.nextInt();
    }

    if (response == 1) {
        vehicleType = VehicleType.CAR;
        while (numPassengerSeats < 4 || numPassengerSeats > 7) {
            System.out.println("Please enter the number of Passengers: ");
            numPassengerSeats = scan.nextInt();
        }
    } else {
        vehicleType = VehicleType.VAN;
        while (true) {
            System.out.println("Please enter the last maintenance date (dd/mm/yyyy): ");
            String formattedDate = scan.next();
            lastMaintenanceDate = formatDate(formattedDate);
            if (lastMaintenanceDate != null)
                break;
        }
    }

【问题讨论】:

  • java.util.Scanner.nextInt()API documentation 解释了它在什么情况下会抛出什么异常。如果您输入的不是整数,您将获得InputMismatchException。您必须将 nextInt() 语句放在 try 块中,然后捕获异常并适当地处理它。

标签: java error-handling


【解决方案1】:

让我们看看javadoc 换成nextInt()

将输入的下一个标记扫描为 int。对此的调用 nextInt() 形式的方法的行为方式与 调用 nextInt(radix),其中 radix 是 this 的默认基数 扫描仪。

返回:从输入扫描的 int

投掷

输入不匹配异常 - 如果下一个标记与 Integer 正则表达式不匹配,或者超出范围

NoSuchElementException - 如果输入已用尽

IllegalStateException - 如果此扫描仪已关闭

根据 javadoc,如果用户输入 String 而不是 int,它会抛出 InputMismatchException。所以,我们需要处理它。

【讨论】:

    【解决方案2】:

    我认为你没有成功地强制你的程序只接受整数,因为通过使用java.util.Scanner.nextInt(),用户仍然可以输入非整数,但是java.util.Scanner.nextInt() 只会抛出异常。有关可能引发的异常,请参阅this
    我已经制定了一个解决方案来强制您的程序只接受整数。只需按照下面的示例代码:

    示例代码:

    package main;
    
    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) {
            int response = 0;
            Scanner scan = new Scanner(System.in);
            while (response != 1 && response != 2) {
                System.out.println("Please enter 1 for Car or 2 for Van: ");
                try {
                    response = Integer.parseInt(scan.nextLine()); 
                    if (response != 1 && response != 2) {
                        System.out.println("Input is not in choices!");
                    }
                } catch (NumberFormatException e) {
                    System.out.println("Input is invalid!");
                }
            }
            scan.close();
        }
    
    }
    

    【讨论】:

    • 你不能同时“接受”和“抛出异常”。
    • @user207421 看来您误解了我的回答,我没有解释清楚是我的错误。我的意思不是用户仍然可以输入非整数并且程序会抛出异常。我修改了我的答案。如果仍有错误,请发表评论,以便我可以更新/删除它。感谢您的评论!
    猜你喜欢
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多