簡體   English   中英

掃描儀JAVA的一定要求

[英]Scanner JAVA certain requirements

對於我的代碼,我需要制作一個掃描儀來抓取我的學校項目的用戶輸入。 但是,輸入只能是3位數字,否則應該提示用戶再次請求輸入? 我怎樣才能用JAVA做到這一點? 謝謝。

這是我目前擁有的,但它不起作用

    Scanner sc = new Scanner(System.in);

    while(sc.nextInt() > 99 && sc.nextInt() < 1000) {
        int n = sc.nextInt();
    }

我目前有這個,但它不起作用。

在嘗試將其分配給int變量之前,我會驗證您在掃描程序中有一個int。 您可以使用Scanner.hasNextInt()方法執行此操作。

嘗試這樣的東西,看看它是否適用於您的應用程序:

Scanner scanner = new Scanner(System.in);
        int input = 0;

        while(input < 100 || input > 999) {
            System.out.print("Please enter a 3-digit number:");
            if(scanner.hasNextInt()) {
                input = scanner.nextInt();
            }
            else {
                scanner.next();
            }
        }

Scanner.nextInt()將提示您輸入,因此您不應在while條件下使用它。

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while(!(n > 99 && n < 1000)) {
    n = sc.nextInt();
}

這可能有所幫助:

public static void main(String[] args) throws Exception {

    int x;

    Scanner in = new Scanner(System.in);
    System.out.print("Enter a number greater than 99 and less than 1000: ");
    x = in.nextInt();

    while (x >= 1000 || x <= 99) {
        System.out.println("Invalid number: Enter in range");
        x = in.nextInt();
    }

    in.close();

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM