java - 如何解析通过将字符串拆分为 Java 中的 Int 值而获得的数据?
问题描述
我拆分了一个字符串,该字符串是用户输入的密码,只返回数字。我需要确保他们输入的那些数字不是特定数字。但首先,我需要获取返回的数据并将它们转换为 int,以便进行比较。
public static boolean checkPassword(String password){
String digitsRegrex = "[a-zA-Z]+";
int upPass;
String [] splitPass = password.split("[a-zA-Z]+");
for(String pass : splitPass){
try{
upPass = Integer.parseInt(pass);
}
catch (NumberFormatException e){
upPass = 0;
}
System.out.println(upPass);
}
return true;
}
当我运行程序时,我在 catch 中取回了 0(以及字符串密码中的数字),所以我猜尝试不起作用?
解决方案
在您的代码中,upPass
当您遇到不包含任何数字的子字符串时,您设置为 0。这些是空字符串。当密码不以数字开头时会发生这种情况。
您应该忽略它,因为您只需要数字。
示例:abcd12356zz33
- 当您使用正则表达式拆分时,[a-zA-Z]+
您会得到""
,"123456"
和"33"
. 当您尝试将第一个空字符串转换为数字时,您会得到一个NumberFormatException
.
for(String pass : splitPass){
if (!pass.isEmpty()) {
try {
upPass = Integer.parseInt(pass);
System.out.println(upPass);
//Validate upPass for the combination of numbers
} catch (NumberFormatException e) {
throw e;
}
}
}
checkPassword("abcd12356zz33")
印刷
12356
33
推荐阅读
- html - 如何将html特殊特殊字符用作普通字符串
- node.js - 如何在 puppeteer 生成的 PDF 中添加水印?
- c# - 如何以其他随机值每 5 秒旋转一个对象?
- ibm-cloud-infrastructure - 通过数据中心获取 VSI 和 Bare Metal 的创建对象
- javascript - 如何旋转任意角度的图像
- ios - iOS 12 - AppAuth 重定向 URL 不触发 AppDelegate
- bash - Bash 列表理解或映射
- wcf - 如何将数组添加到 WCF 数据协定?
- python - 使用 argparse 时出现“无效选择”错误
- ios - 将我的项目文件夹移动到另一个位置,现在 xcworkspace 无法与我的主项目一起打开