【发布时间】:2021-09-23 21:54:36
【问题描述】:
我正在尝试将数组的两个部分相加以形成一个 int 值。我正在使用 Luhn 算法来确定一张信用卡是一张有效的信用卡。我们只使用 6 位数的信用卡,以确保没有人输入真实的信用卡号码。我感到困惑的部分是当我去拆分一个大于 10 的数字并将它加在一起时。例如,如果算法要给我 12,我需要将它分成 1 和 2,然后将它们加在一起等于 3。我相信我目前在代码中将其拆分,但是当我将它们加在一起时,我得到了一些数字从那以后就没有了。这是一段代码,其中有一些注释。
我在某些地方打印了数字,以向自己展示某些地方正在发生的事情。我还添加了一些 cmets 说打印出来的数字是预期的,还有一些 cmets 用于当没有我预期的东西时
int[] cardNumber = new int[]{ 1,2,3,4,5,5};
int doubleVariablesum = 0;
int singleVariablesum = 0;
int totalSum = 0;
int cutOffVar = 0;
String temp2;
for (int i = cardNumber.length - 1; i >= 0;) {
int tempSum = 0;
int temp = cardNumber[i];
temp = temp * 2;
System.out.println("This is the temp at temp * 2: " + temp);
temp2 = Integer.toString(temp);
if (temp2.length() == 1) {
System.out.println("Temp2 char 0: "+ temp2.charAt(0));
// this prints out the correct number
// Example: if there number should be 4 it will print 4
tempSum = temp2.charAt(0);
System.out.println("This is tempSum == 1: " + tempSum);
// when this goes to add temp2.charAt(0) which should be 4 it prints out //something like 56
} else {
System.out.println("TEMP2 char 0 and char 1: " + temp2.charAt(0) + " " + temp2.charAt(1));
// 这会成功打印出正确的数字
tempSum = temp2.charAt(0) + temp2.charAt(1);
System.out.println("This is tempSum != 1: " + tempSum);
// but here it when I try to add them together it is giving me something
// like 97 which doesn't make since for the numbers I am giving it
}
doubleVariablesum = tempSum + doubleVariablesum;
System.out.println("This is the Double variable: " + doubleVariablesum);
System.out.println();
i = i - 2;
}
【问题讨论】: