繁体   English   中英

Java:从INT的其余部分拆分最后一位数字

[英]Java: Split last digit from the rest of the INT

我有下一个代码,它得到一个数字,我需要将该数字拆分为部分,firstPart应该是没有最后一个数字的整数,而secondPart应该只是原始数字的最后一个数字。

public Boolean verificationNumberFiscalId(String fiscalId) {

        // Trying to do a better wa yto do it
        Integer firstPart = fiscalId.length()-1;
        Integer secondPart = ??????????;



        // My old logic
        String NitValue = "";
        for (Integer i = 0; i < fiscalId.length()-1; i++) {
            NitValue = fiscalId.substring(i,1);
        }

        Integer actualValueLength = fiscalId.length()-1;        
        String digitoVerificador = fiscalId.substring(actualValueLength,1);
        return this.generateDigitoVerification(NitValue) == digitoVerificador;
    }
    /** 
     * @param nit
     * @return digitoVerificador
     * @comment: Does the math logic
     */
    public String generateDigitoVerification(String nit) {        
        Integer[] nums = { 3, 7, 13, 17, 19, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71 };

        Integer sum = 0;

        String str = String.valueOf(nit);
        for (Integer i = str.length() - 1, j=0; i >= 0; i--, j++) {
            sum += Character.digit(str.charAt(i), 10) * nums[j];
        }

        Integer dv = (sum % 11) > 1 ? (11 - (sum % 11)) : (sum % 11);
        return dv.toString();
    }

你能告诉我一个更好的方法吗? 谢谢!

int x = 1343248724;
int firstpart = x/10;
int secondpart = x%10;

System.out.println(firstpart);
System.out.println(secondpart);

Mod(%)给出剩余部分,如果你修改10 Divide将丢弃最后一个数字,它将是最后一个数字。 这样你就不必实际搜索字符串。

做所有长度的事情对我来说似乎有些过分

哦,并将你的参数作为我将使用的int

Interger.decode(fiscalId);

这是你如何得到整数:

Integer firstPart = Integer.valueOf(
                        fiscalId.substring(0,fiscalId.length()-1));
Integer secondPart = Integer.valueOf(
                        fiscalId.substring(fiscalId.length()-1));

但我建议改为:

int firstPart = Integer.parseInt(fiscalId.substring(0,fiscalId.length()-1));
int secondPart = Integer.parseInt(fiscalId.substring(fiscalId.length()-1));
  1. 将您的号码转换为字符串。 使用String.valueOf()
  2. 将该字符串拆分为两个字符串。 首先,查看原始字符串的长度。 对于长度n ,使用它的子串(0,n-1)作为第一个新字符串。 将最后一个字符(n)用于第二个字符串
  3. 使用Integer.valueOf()将两个字符串转换回整数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM