[英]Checking if a string contains only digits and then setting it only if it doesn't contain characters other than digits
/**
* Set the person's mobile phone number
*/
public void setMobile(String mobile) {
for (int i = 0; i < mobile.length(); i++) {
if (!Character.isDigit(mobile.charAt(i))) {}
}
this.mobile = mobile;
}
因此,我基本上需要確保該字符串僅包含數字,並且如果該字符串包含非數字,則該方法什么也不做。 我的問題是,如果一串數字中有一個隨機字符,即“ 034343a45645”,它將仍然設置該方法。 任何幫助表示贊賞,謝謝!
您可以使用String.matches(String regex)
:
boolean onlyDigits = mobile.matches("[0-9]+");
使用for循環,當發現非數字時,您可以中斷。
boolean onlyDigits = true;
for (int i = 0; i < mobile.length(); i++) {
if (!Character.isDigit(mobile.charAt(i))) {
onlyDigits = false;
break;
}
}
除了打破循環,您還可以返回。 聽起來您不希望之后發生任何其他事情。 這樣就消除了對onlyDigits
變量的需求。
請注意,如果mobile.length() == 0
則相對於上述for循環, onlyDigits
仍然為true
。 因此,假設如果mobile
是一個空字符串,則onlyDigits
應該為false
,則可以這樣初始化它:
boolean onlyDigits = !mobile.isEmpty()
檢查后,如果onlyDigits
為true
,則可以分配它。
if (onlyDigits)
this.mobile = mobile;
您有兩個問題:
第一:如果條件為假,則您沒有退出循環
第二:為什么要使用循環嘗試像這樣實現tryParse
boolean tryParseInt(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
if(tryParseInt(mobile)){
this.mobile = mobile;
}
添加一個boolean letterFound;
然后在你的for循環
每當找到字母時,請使用else
語句將letterFound
設置為true
然后立即在您的else
語句中停止循環i=mobile.length()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.