简体   繁体   English

如果用户输入String而不是Int,有什么可能的例外情况?

[英]What possible exceptions are there if User enters String instead of Int?

I am just playing with Java.I'm trying to force my program to only accept number digits 1 and 2. I believe I have successfully done this using a while loop (please correct me if I'm wrong). 我只是在玩Java。我试图迫使我的程序只接受数字1和2。我相信我已经使用while循环成功完成了此操作(如果我输入错了,请更正我)。 But how do I go about printing an error statement if the user enters a string. 但是,如果用户输入字符串,我该如何打印一条错误语句。 eg: "abc". 例如:“ abc”。

My code: 我的代码:

    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;
        }
    }

Let's have a look at javadoc for nextInt() : 我们来看一下nextInt() javadoc

Scans the next token of the input as an int. 将输入的下一个标记扫描为int。 An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner. 调用nextInt()形式的此方法的行为与调用nextInt(radix)的行为完全相同,其中radix是此扫描器的默认基数。

Returns : the int scanned from the input 返回 :从输入扫描的int

Throws : 抛出

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range InputMismatchException-如果下一个标记与Integer正则表达式不匹配或超出范围

NoSuchElementException - if input is exhausted NoSuchElementException-如果输入已用尽

IllegalStateException - if this scanner is closed IllegalStateException-如果此扫描仪已关闭

As per javadoc, it throws InputMismatchException if the user enters a String instead of an int . 根据javadoc,如果用户输入String而不是int ,它将抛出InputMismatchException So, we need to handle it. 因此,我们需要处理它。

I think you have not successfully force your program to accept just integers since by using java.util.Scanner.nextInt() , user can still be able to input non integers, however java.util.Scanner.nextInt() will just throw an exception. 我认为您尚未成功强制程序接受整数,因为通过使用java.util.Scanner.nextInt() ,用户仍然可以输入非整数,但是java.util.Scanner.nextInt()只会抛出一个整数。例外。 Refer to this for possible exception thrown. 请参阅以引发可能的异常。
I have made a solution to force your program to accept just integers. 我已提出一种解决方案,以强制您的程序仅接受整数。 Just follow the sample code below: 只需遵循以下示例代码:

Sample code: 样例代码:

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();
    }

}

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

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