如何在字符串中切换奇偶数字?Luhn算法信用卡验证代码排错
问题分析与修复方案
Hey there! Let's dig into why your code keeps repeating a single digit and get that credit card validation logic back on track.
1. 为什么会重复输出单个数字?
The root cause is this line inside your loop:
currentDigit = Integer.parseInt(potentialCCN.substring(potentialCCN.length()-1));
No matter what i value your loop is on, you're always grabbing the last character of the original credit card string (potentialCCN). That's why you see the same digit over and over—you never actually access different positions in the reversed string you created!
2. 其他偏离Luhn算法预期的问题
Your code also misses several key steps you outlined in your plan:
- You didn't remove the last digit from
potentialCCN(this is the check digit, which should be set aside and used at the end of validation) - Your loop uses
i += 2, which skips half the digits instead of iterating through every one - The
isOddDigittoggle logic is out of sync with your intended "multiply digits in odd positions by 2" rule
修正后的代码
Here's your code updated to match your planned steps, with fixes for all the issues:
package creditCard; import java.util.Scanner; public class Program2CCValidation { public static void main(String[] args) { Scanner scan = new Scanner(System.in); boolean validCreditCard = false; while (!validCreditCard) { System.out.print("Please enter a credit card number: "); String potentialCCN = scan.nextLine(); // Extract the last check digit and remove it from the main number int lastDigit = Integer.parseInt(potentialCCN.substring(potentialCCN.length() - 1)); potentialCCN = potentialCCN.substring(0, potentialCCN.length() - 1); // Reverse the remaining digits String reversedCCN = ""; for (int i = potentialCCN.length() - 1; i >= 0; i--) { reversedCCN += potentialCCN.charAt(i); } boolean isOddPosition = false; // Start with even position, toggle first int currentDigit = 0; int sum = 0; // Iterate through every digit in reversed string for (int i = 0; i < reversedCCN.length(); i++) { // Get current digit from reversed string (not original!) currentDigit = Integer.parseInt(String.valueOf(reversedCCN.charAt(i))); // Toggle position flag to target odd positions in reversed string isOddPosition = !isOddPosition; if (isOddPosition) { currentDigit *= 2; // Subtract 9 if value exceeds 9 if (currentDigit > 9) { currentDigit -= 9; } } // Add processed digit to total sum sum += currentDigit; } // Validate using the check digit int total = sum + lastDigit; validCreditCard = (total % 10 == 0); // Notify user of result if (validCreditCard) { System.out.println("This is a valid credit card number!"); } else { System.out.println("Invalid credit card number. Please try again."); } } scan.close(); } }
关键修正点说明
- We now extract the check digit and remove it from the main number before processing, as per Luhn's requirements
- We iterate through every digit in
reversedCCN(no more skipping withi += 2) - The
isOddPositionflag is toggled at the start of each loop to correctly target the odd positions in the reversed string (which correspond to even positions in the original card number) - We calculate the total sum, add the check digit, and verify if the total is divisible by 10 to confirm validity
内容的提问来源于stack exchange,提问作者shinysquirrell
相关产品推荐
相关产品推荐

