簡體   English   中英

用戶輸入的java驗證問題

[英]Problems with java validation for user input

我知道有很多關於 Java 輸入驗證的問題,但無論我閱讀什么,我似乎都無法讓它發揮作用。 我希望用戶將出生日期輸入為 (MM DD YYYY)。 我想驗證一下

  1. 用戶只輸入數字
  2. 他們做了正確的位數和
  3. 數字落在正確的范圍內。

我第一次嘗試使用 int 變量,但似乎無法將hasNextInt()與數字長度和范圍結合起來。 然后我看到一個帖子說要做 String 變量,然后使用Integer.parseInt() 我認為如果我使用(!month.matches("0[1-9]") || !month.matches("1[0-2]")這會很好用,因為它似乎滿足了我所有的驗證願望. 我在 while 語句中嘗試了這個,但它陷入了無限循環。然后我嘗試將該代碼更改為 if...else 語句並用while(false)語句將其包圍。但是,它現在拋出錯誤而不是去我的聲明說修復你的錯誤。這是我的代碼目前的樣子:

import java.util.Scanner; //use class Scanner for user input

public class BD {
    private static Scanner input = new Scanner(System.in); //Create scanner

    public static void main(String[] args){
        //variables
        String month;
        int birthMonth;
        String day;
        int birthDay;
        String year;
        int birthYear;
        boolean correct = false;

        //prompt for info
        System.out.print("Please enter your date of birth as 2 digit "+
            "month, 2 digit day, & 4 digit year with spaces in-between"+
            " (MM DD YYYY): ");
        month = input.next();
        //System.out.printf("%s%n", month);  //test value is as expected
        day = input.next();
        year = input.next();

        //validate month value
        while (correct = false){
            if(!month.matches("0[1-9]") || !month.matches("1[0-2]")){
                System.out.println("Please enter birth month as "+
                    "a 2 digit number: ");
                month = input.next();
                //System.out.printf("%s%n", month);
            }
            else {
                correct = true;
            }
        }

        //turn strings into integers
        birthMonth = Integer.parseInt(month);
        birthDay = Integer.parseInt(day);
        birthYear = Integer.parseInt(year);

        //check values are correct
        System.out.printf("%d%d%d", birthMonth, birthDay, birthYear);
    }
}

任何幫助將不勝感激。 我還想嘗試在沒有任何 try/catch 塊的情況下進行此驗證,因為它們看起來太大了。 謝謝!

如果你想使用正則表達式,你可以試試這個

    while(!(Pattern.matches("(0)[1-9]{1}|(1)[0-2]",month)))
    {
           System.out.println("Enter again \n");
           month=input.next();
    }

要使此代碼正常工作,您需要在程序開頭使用它來包含正則表達式包

  import java.util.regex.*;

我們的正則表達式分為兩部分“ (0)[1-9]{1} ”,這將首先確保字符串包含“0”,然后是 1-9 之間的任何數字。 而“ {1} ”將確保它只出現一次。

如果需要,類似地編寫日和年的代碼。

使用DateTimeFormatter是這樣的:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM dd yyyy");

try {
    LocalDate date = LocalDate.parse(input, formatter);
} catch (DateTimeParseException e) {
    // Thrown if text could not be parsed in the specified format
}

暫無
暫無

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

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