[英]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.