簡體   English   中英

如果用戶輸入String而不是Int,有什么可能的例外情況?

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

我只是在玩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;
        }
    }

我們來看一下nextInt() javadoc

將輸入的下一個標記掃描為int。 調用nextInt()形式的此方法的行為與調用nextInt(radix)的行為完全相同,其中radix是此掃描器的默認基數。

返回 :從輸入掃描的int

拋出

InputMismatchException-如果下一個標記與Integer正則表達式不匹配或超出范圍

NoSuchElementException-如果輸入已用盡

IllegalStateException-如果此掃描儀已關閉

根據javadoc,如果用戶輸入String而不是int ,它將拋出InputMismatchException 因此,我們需要處理它。

我認為您尚未成功強制程序接受整數,因為通過使用java.util.Scanner.nextInt() ,用戶仍然可以輸入非整數,但是java.util.Scanner.nextInt()只會拋出一個整數。例外。 請參閱以引發可能的異常。
我已提出一種解決方案,以強制您的程序僅接受整數。 只需遵循以下示例代碼:

樣例代碼:

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