簡體   English   中英

java掃描儀:如何防止輸入垃圾郵件

[英]java scanner: how prevent enter spam

我有一個用戶輸入驗證 function:

public int UserChoiceValidate() {
    Scanner sc = new Scanner(System.in);
    int choice;
    do {
        System.out.print("Please enter your choice: ");
        while (!sc.hasNextInt()) {
            System.out.print("Input invalid, please retry: ");
            sc.nextLine(); // consume left over
        }
        choice = sc.nextInt();
        if (choice <= 0 || choice > 5) {
            System.out.println("Choice not included, please retry");
        }
    } while (choice <= 0 || choice > 5);
    return choice;
}

代碼會重復

輸入無效,請重試:輸入無效,請重試:輸入無效,請重試:

當我輸入垃圾郵件然后輸入無效輸入時。

如何修復此錯誤而不必將其重寫為讀取字符串而不是 int。 我有很多具有相同結構的函數,我想避免重寫它們。

我不確定“將其重寫為字符串驗證”是什么意思,您目前忽略了用戶提供的任何不是int的輸入; 如果你想特別對待“輸入垃圾郵件”,你可以做類似的事情

System.out.print("Please enter your choice: ");
while (!sc.hasNextInt()) {
    String line = sc.nextLine();
    if (line.isEmpty()) {
        continue;
    }
    System.out.print("Input invalid, please retry: ");
}

暫無
暫無

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

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