首页 > 解决方案 > 如何解析通过将字符串拆分为 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(以及字符串密码中的数字),所以我猜尝试不起作用?

标签: javaarraysparseint

解决方案


在您的代码中,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

推荐阅读