2014-10-19 48 views
1

我有一個問題,我試圖讓一個參數匹配格式'Uddd',其中'U'必須是字母U和'ddd'可以是從0-9的任何3位數字。無法讓java匹配正則表達式匹配()

我當前的代碼:

//borrow method 
public boolean borrow(String borrowerID) 
{ 
    //if the borrower ID matches the format 'Uddd' 
    if (borrowerID.matches("U([0-9]{3})")) 
    { 
     //if the status is available 
     if (status == 'A') 
     { 
      this.borrowerID = borrowerID; 
      this.status = 'O'; 
      this.dateBorrowed = currentDate; 
      return true; 
     } 
     //is not available 
     else 
     { 
      return false; 
     } 
    } 
    //does not match format 
    else 
    { 
     return false; 
    } 
} 

出於某種原因,它不是驗證正確。當我嘗試輸入'1'作爲參數時,它仍然返回true。

有什麼我失蹤了嗎?

回答

4

它不應該是可能該方法返回true如果輸入的是"1"。我只能建議你確保你通過"1",並且該方法是被調用的方法。

,可以用一個簡單的調試語句在頂部做,是這樣的:

System.out.println ("Calling correct function with [" + borrowerId + "]"); 

在函數的開始。

我也建議一點點清理,使功能更容易碼,讀,沿着線:

// borrow method 
public boolean borrow(String borrowerID) 
{ 
    // Temp debug statement. 

    // System.out.println ("borrow [" + borrowerId + "]"); 

    // "Not available" or "invalid borrower" means reject request. 

    if (status != 'A') 
     return false; 

    if (! borrowerID.matches("U([0-9]{3})")) 
     return false; 

    // Okay to borrow. 

    this.borrowerID = borrowerID; 
    this.status = 'O'; 
    this.dateBorrowed = currentDate; 

    return true; 
} 

這比那些return-else-do-something構建更清潔了很多,它遵循「快速失敗」的範例。

有些人往往不喜歡多個返回點,但通常是因爲他們不明白爲什麼他們被認爲是不好(意大利麪代碼)。有了這樣一個簡短的功能,它不會造成問題。

+0

hrmm,我認爲問題在於我的其他子課程。 另外,我注意到你的條件語句不使用任何大括號。這僅適用於單行條件語句嗎? – antonlab 2014-10-19 10:08:13

+0

此外,如果例如在您修改的代碼中,它檢測到狀態不是'A',它會返回false,然後停止代碼? – antonlab 2014-10-19 10:12:42

+0

@antonlab,是的,如果它是單行「塊」,則不需要大括號。此外,「返回」中的內容將跳過其餘的語句。 – paxdiablo 2014-10-19 10:27:48

1

其實這不是。一有機會輸入1不會返回true,但它返回false.may是你的狀態等於「A」,應該是理由返回true

String borrowerID="1";  
boolean matches = borrowerID.matches("U([0-9]{3})"); 
System.out.println(matches); 

輸出>>

false 

,如果你只是想找到的是正則表達式匹配與否,然後使用這個。或者把SOUT和支票上的地位value.definitely它應該是一個

if (borrowerID.matches("U([0-9]{3})")) { 

    return true; 

} else { 

    return false; 
} 
2

我用你的正則表達式得到了很好的結果:「1」 - > false,「UU123」 - > false,「U1234」 - > false,「U132」 - > true。

但你可以使用\ d代替[0-9]:

borrowerID.matches("U(\\d{3})") 
0

沒有您regex

System.out.println("U888".matches("U([0-9]{3})")); 

輸出沒有問題true

System.out.println("1".matches("U([0-9]{3})")); 

輸出false

嘗試debug你的代碼,很少breakpoint裏面你borrow function

您也可以優化您喜歡

if (borrowerID.matches("U([0-9]{3})") && (status == 'A')) { 
     this.borrowerID = borrowerID; 
     this.status = 'O'; 
     this.dateBorrowed = currentDate; 
     return true; 
} else { 
    return false; 
} 

我不明白onething,正在檢查的status againist「A」和內部assignin「0」,是否有意義?(反正是高達你)

+0

重新設置狀態,我會建議'a'可用,並且'o'出現了,例如,如果您認爲就圖書館書籍而言,代碼是有意義的。您只能借用可用的東西,並且只有在您的身份證件有效時(您擁有圖書證)纔可以借閱。 – paxdiablo 2014-10-19 10:34:52

+0

@paxdiablo對不起,我認爲它爲零,無論如何他可以引入一個'boolean'或'enum'是一個不錯的選擇,並且更有意義,爲什麼你要爲'A'和'O'去混淆新讀者對? – 2014-10-19 10:43:15