java的scanner怎樣處理輸入超時(shí)

小樊
81
2024-09-24 01:23:00
欄目: 編程語言

在Java中,使用Scanner類處理輸入超時(shí)時(shí),可以通過設(shè)置超時(shí)參數(shù)來實(shí)現(xiàn)。以下是一個(gè)示例:

import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;

public class ScannerTimeoutExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 設(shè)置輸入超時(shí)時(shí)間(單位:毫秒)
        scanner.setTimeout(3000); // 設(shè)置為3秒

        System.out.println("請(qǐng)輸入一個(gè)整數(shù)(輸入超時(shí)時(shí)間為3秒):");

        try {
            int input = scanner.nextInt();
            System.out.println("輸入的整數(shù)是:" + input);
        } catch (InputMismatchException e) {
            System.out.println("輸入超時(shí),請(qǐng)重新運(yùn)行程序并輸入一個(gè)整數(shù)。");
        } catch (NoSuchElementException e) {
            System.out.println("輸入超時(shí),請(qǐng)重新運(yùn)行程序并輸入一個(gè)整數(shù)。");
        } finally {
            scanner.close();
        }
    }
}

在這個(gè)示例中,我們?cè)O(shè)置了Scanner的輸入超時(shí)時(shí)間為3秒。如果在3秒內(nèi)沒有輸入任何內(nèi)容,程序?qū)伋?code>NoSuchElementException異常。如果輸入的不是整數(shù),程序?qū)伋?code>InputMismatchException異常。在這兩種情況下,我們都捕獲了異常并給出了相應(yīng)的提示信息。

0