所以这是任务:
信用卡号码 使用 8 位数字检查 • 从最右边的数字开始,形成所有其他数字的总和。例如,如果信用卡号是 4358 9795,那么您将形成总和 5 + 7 + 8 + 3 = 23。 • 将前面步骤中未包括的每个数字加倍。添加结果数字的所有数字。例如,对于上面给出的数字,将数字加倍,从倒数第二个开始,得到 18 18 10 8。将这些值中的所有数字相加得到 1 + 8 + 1 + 8 + 1 + 0 + 8 = 27。 • 将前面两个步骤的总和相加。如果结果的最后一位为 0,则该数字有效。在我们的例子中,23 + 27 = 50,所以这个数字是有效的。--有效/无效?
我已经为这些方法创建了一个测试程序和一个单独的程序。一切都成功编译,所以不应该有任何技术错误,但即使我输入有效的卡号,程序也会返回该号码无效,所以我假设实际算法有问题,但我很新这让我无法弄清楚它是什么。
import java.util.Scanner;
public class CreditCardTester{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String retry = ("y");
String n = null;
while(retry.equalsIgnoreCase("y")){ // allows program to keep running even if the user enters in a capital Y
int lengthCheck = 1;
System.out.println("Please enter your 8-digit credit card number");
// check to see whether the input number is exactly 8 digits
while(lengthCheck==1){
n = scanner.next();
if(n.length()==8)
lengthCheck=0;
else
System.out.println("Please make sure the credit card number you have entered is 8 digits");
} // end inner while loop
// instantiate CardNumber and check validity
CardNumber number = new CardNumber(n);
number.check();
if (number.isValid())
System.out.println("The number you entered is a valid credit card number.");
else
System.out.println("The number you entered is not a valid credit card number. Would you like to enter in another number? (y/n)");
retry = scanner.next();
} // end outer while loop
}
}
和单独的班级
public class CardNumber {
private String number;
private boolean valid;
public CardNumber(String n){
number = n;
valid = true;
}
private void check1(){
int a = Integer.parseInt(number.substring(7));
int b = Integer.parseInt(number.substring(5,6));
int c = Integer.parseInt(number.substring(3,4));
int d = Integer.parseInt(number.substring(1,2));
int oddsum = a + b + c + d;
int e = (Integer.parseInt(number.substring(6,7))) * 2;
int f = (Integer.parseInt(number.substring(4,5))) * 2;
int g = (Integer.parseInt(number.substring(2,3))) * 2;
int h = (Integer.parseInt(number.substring(0,1))) * 2;
String ee = String.valueOf(e);
String ff = String.valueOf(f);
String gg = String.valueOf(g);
String hh = String.valueOf(h);
int evensum = (Integer.parseInt(ee.substring(0))) + (Integer.parseInt(ff.substring(0))) + (Integer.parseInt(gg.substring(0))) + (Integer.parseInt(hh.substring(0)));
int totalsum = evensum + oddsum;
if (!(totalsum%10 == 0))
valid=false;
}
public void check(){
check1();
}
public boolean isValid(){
return valid;
}
}
我相信还有一个更好的方法可以做到这一点,所以所有的建议都值得赞赏!