信用卡 Long/String 验证

Credit Card Long/String Validation

我正在处理信用卡号验证应用程序。

我可以输入有效数字或无效数字,但输出从不接收数据并将其读取为有效。我正在尝试找出验证信用卡的正确算法。

以下是我想要的结果。我需要知道我在循环的哪个点,或者我对 long 与 string 的使用是否搞砸了,这会导致输出始终读取为无效。

示例 1:

Enter a credit card number: 4246345689049834

4246345689049834 is invalid

示例 2:

Enter a credit card number: 4388576018410707

4388576018410707 is valid

但是,在我的代码中,我得到以下输出

示例 1:

Enter a credit card number: 4246345689049834

4246345689049834 is invalid

示例 2:

Enter a credit card number: 4388576018410707

4388576018410707 is invalid 

代码:

    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter Credit Card Number for Validation: ");
        long number = input.nextLong();

        long total = sumOfEvenPlaces(number) + sumOfOddPlaces(number);

        if (isValid(total)) {
            System.out.println(number + " is valid");
        } else {
            System.out.println(number + " is invalid");
        }
    }

    public static boolean isValid(long total) {
        if (total % 10 == 0) {
            return true;
        }
        return false;
    }

    public static int sumOfEvenPlaces(long number) {
        int sum = 0;
        int remainder;
        number %= 10;
        while (number % 10 != 0 || number / 10 != 0) {
            remainder = (int) (number % 10);

            sum = sum + getDigit(remainder * 2);
            number /= 100;
        }
        return sum;
    }

    public static int getDigit(int number) {
        if (number > 9) {
            return (number % 10 + number / 10);
        }
        return number;
    }

    public static int sumOfOddPlaces(long number) {
        int sum = 0;
        int remainder;

        while (number % 10 != 0 || number / 10 != 0) {
            remainder = (int) (number % 10);
            sum = sum + getDigit(remainder);
            number /= 100;
        }
        return sum;
    }
}

你的sumOfEvenPlaces()sumOfOddPlaces()方法都有错误。

sumOfEvenPlaces(long number)你必须改变

 number %= 10; 

 number /= 10;

您只能使用数字 / 10 跳过一个数字,而不是数字 % 10

并在两个函数中更改

 while (number % 10 != 0 || number / 10 != 0)

 while (number > 0)

通过使用 while (number > 0) 循环将工作直到处理完 number 中的所有数字。

试试这些修改后的方法,这会奏效:-

public static int sumOfEvenPlaces(long number) {
    int sum = 0;
    int remainder;
    number /= 10;          // change 1
    while (number > 0) {   // change 2
        remainder = (int) (number % 10);
        sum = sum + getDigit(remainder * 2);
        number /= 100;
    }
    return sum;
}

public static int sumOfOddPlaces(long number) {
    int sum = 0;
    int remainder;

    while (number > 0) {   // change 3 
        remainder = (int) (number % 10);
        sum = sum + getDigit(remainder);
        number /= 100;
    }
    return sum;
}

输出:-

Enter Credit Card Number for Validation: 
 4246345689049834
4246345689049834 is invalid