[英]how to add two integers in a number
I am writing a credit card validation program. 我正在写一个信用卡验证程序。 I am trying to see if a product is more that 1 digit long (ie: 10), if it is I need to add the two integers together.
我试图看一个产品是否超过1位数(即:10),如果是,我需要将两个整数加在一起。 For example 10 would be
1 + 0
, which equals 1, how do I do this? 例如10将是
1 + 0
,等于1,我该怎么做?
This is what I have so far: 这是我到目前为止:
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!!");
}
}
}
}
Rather than re-inventing the wheel you could have a look at the Luhn algorithm which is a widely used checksum algorithim used to validate credit card numbers. 您可以查看Luhn算法 ,而不是重新发明轮子, Luhn算法是一种广泛使用的校验和算法,用于验证信用卡号。 Here is a Java version .
这是一个Java版本 。
It looks like you're trying to implement the Luhn checkdigit algorithm . 看起来你正在尝试实现Luhn checkdigit算法 。
Try the apache commons LuhnCheckDigit()
utility method of the Apache commons-validator library . 尝试Apache commons-validator库的apache commons
LuhnCheckDigit()
实用方法。
您可能希望首先将整数拆分为数字: 将int值拆分为单独的数字
If Blender's comment is correct, you could do it like this: 如果Blender的评论是正确的,你可以这样做:
int num=123; // or whatever
String str=Integer.toString(num);
int total=0;
if(str.length()>1){
for(int i=0; i<str.length(); i++){
total+=Integer.parseInt(str.charAt(i));
}
}
System.out.println(total);
(I haven't run this, so there are probably some errors in there) (我没有运行它,因此可能存在一些错误)
I think a simple way would be 我认为一个简单的方法
if (num1 > 9) num1 = num1-9
This works if you look at how the original numbers look after multiplying by 2. 如果您查看原始数字乘以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
I think your code to calculate the total should be 我认为你的代码应该计算总数
int totalSum = 0;
for (i=0; i<num.length; i+=2) {
totalSum+=num[i+1];
if (num[i+2]>4) {
totalSum+=1+((num[i+2]*2) % 10);
} else {
totalSum+=num[i+2]*2;
}
}
This avoids any slow string conversions. 这可以避免任何慢速字符串转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.