我在尝试获取参数以匹配格式“Uddd”时遇到问题,其中“U”必须是字母 U,“ddd”可以是 0-9 中的任意 3 位数字。
我当前的代码:
//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。
有什么我想念的吗?
最佳答案
如果输入是 "1"
,该方法应该不可能返回 true
。我只能建议您确保您传入 “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
结构要简洁得多,并且它遵循“快速失败”范式。
有些人倾向于不喜欢多个返回点,但这通常是因为他们不理解为什么它们被认为是糟糕的(意大利面条代码)。使用像这样的短函数,它不会造成问题。
关于java - 无法让 java 将正则表达式与 matches() 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26449204/