我正在编写一个信用卡验证程序。我正在尝试查看产品的长度是否超过1位数(即10),如果需要的话,我需要将两个整数加在一起。例如10将是1 + 0,等于1,我该怎么做?

这是我到目前为止的内容:

public class CreditCard{
public static void main(String args[]){

    //Take in a 16 digit credit card number
    Scanner in=new Scanner (System.in);
    int num[]=new int[16];
    int i=0;


    for (i=0;i<num.length;i++) {
        System.out.println("Please enter a 16 digit credit card number");
        num[i]=in.nextInt();

    }
    if (num.length < 16 || num.length > 16)
        {
            System.out.println("Invalid");
        }
     else
    {

        //multiply every other number by 2, starting with place 16, and find the sum(sum1)
         int num1 = (num[16] * 2);
         int num2 = (num[14] * 2);
         int num3 = (num[12] * 2);
         int num4 = (num[10] * 2);
         int num5 = (num[8] * 2);
         int num6 = (num[6] * 2);
         int num7 = (num[4] * 2);
         int num8 = (num[2] * 2);

         if( num1 > 9)

         int sum1 = (num[16] * 2) + (num[14] * 2) + (num[12] * 2) + (num[10] * 2) + (num[8] * 2) + (num[6] * 2) + (num[4] *2) + (num[2] *2);
         int sum2 = (num[15] + num[13] + num[11] + num[9] + num[7] + num[5] + num[3] + num[1]);

        int totalSum = sum1 + sum2;
        if (totalSum % 10 != 0)
        {
            System.out.println("Invalid card number!!");
        }
        else

        {
            System.out.println(" Valid Credit Card Number!!");


        }

      }
}
}

最佳答案

我认为一个简单的方法是

if (num1 > 9) num1 = num1-9


如果您查看原始数字乘以2后的样子,则此方法有效。

num  num*2  result
0    0      0
1    2      2
2    4      4
3    6      6
4    8      8
5    10     1
6    12     3
7    14     5
8    16     7
9    18     9

关于java - 如何将两个整数相加,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13870191/

10-10 17:04