检查字符串是否仅包含数字,然后仅当它不包含数字以外的字符时才设置它

hK-*_*hK- 4 java for-loop

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)

所以我基本上需要确保字符串只包含数字,如果它包含非数字,则该方法什么都不做。我遇到的问题是,如果一串数字中有一个随机字符,即“034343a45645”,它仍然会设置该方法。任何帮助表示感谢!

Val*_*tin 7

你可以使用String.matches(String regex)

boolean onlyDigits = mobile.matches("[0-9]+");
Run Code Online (Sandbox Code Playgroud)

使用 for 循环,您可以在找到非数字时中断。

boolean onlyDigits = true;
for (int i = 0; i < mobile.length(); i++) {
    if (!Character.isDigit(mobile.charAt(i))) {
        onlyDigits = false;
        break;
   }
}
Run Code Online (Sandbox Code Playgroud)

您也可以直接返回,而不是跳出循环。听起来你不希望之后发生任何其他事情。从而消除了对变量的需要onlyDigits

请注意,if mobile.length() == 0thenonlyDigits仍然true与上面的 for 循环相关。所以假设onlyDigits应该是falseifmobile是一个空字符串,那么你可以这样初始化它:

boolean onlyDigits = !mobile.isEmpty()
Run Code Online (Sandbox Code Playgroud)

onlyDigits检查后,如果是,则可以分配它true

if (onlyDigits)
    this.mobile = mobile;
Run Code Online (Sandbox Code Playgroud)