簡體   English   中英

如何在 java 中僅接受用戶的指定輸入

[英]How to take only specified input from the user in java

我想從 java 中的用戶那里獲取輸入,並且輸入僅為0 和 1。如果用戶輸入的不是 0 和 1,則掃描儀必須拒絕這些數字。請解決我的問題。

掃描儀 class 提供了一種檢查輸入是否為 Integer 的方法。 如果是integer,檢查是0還是1,否則重新輸入

Scanner scanner = new Scanner(System.in);

        int num;
        do {
            System.out.print("Please enter input 0 or 1: ");
            while (!scanner.hasNextInt()) {
                String input = scanner.next();
                System.out.printf("Pls enter a valid number");
            }
            num = scanner.nextInt();
        } while (num < 0 || num > 1);

只是另一種方式(許多)可以做到這一點:

Scanner userInput = new Scanner(System.in);
String num = "";
while (num.isEmpty()) {
    System.out.print("Please enter either 0 or 1 (q to quit): -> ");
    num = userInput.next();
    if (num.equalsIgnoreCase("q")) {
        System.out.println("Quiting - Bye Bye");
        return;
    }
    // Does the entry match either a 0 or a 1?
    if (!num.matches("[01]")) {
        // No...
        System.out.println("Invalid Entry! (" + num + ") Try again..." 
                           + System.lineSeparator());
        num = "";   // Empty num so to re-loop.
    }
    // Yes, so exit loop with num containing the valid number of 0 or 1.
}
int number = Integer.parseInt(num); // Convert num to integer
System.out.println("The number you entered is:   " + number);    // Display number in Console

暫無
暫無

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

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