6.31题目
题目描述
6.31(金融应用:信用卡号的合法性验证)信用卡号遵循某种模式。一个信用卡号必须是13到16位的整数,它的开头必须是:
- 4,指Visa卡
- 5,指Master卡
- 37,指American Express卡
- 6,指Discover卡
1954年,IBM的Hans Luhn提出一种算法,用于验证信用卡号的有效性。这个算法在确定输入的卡号是否正确,或者这张信用卡是否被扫描仪正确扫描方面是非常有用的。遵循这个方法……(假设卡号为4388576018402626):
- 从右往左偶数位数字翻倍。(如果翻倍之后是两位数则将两位加在一起得到一位数)
- 将第一步得到的所有一位数相加
- 将从右往左的奇数位相加
- 2、3步结果相加
- 如果第4步结果能被10整除,则为合法;反正为非法
如:号码4388576018402626非法,4388576018410707合法
编写程序,提示用户输入一个long型整数的信用卡号码,显示这个数字是合法的还是非法的
使用下面的方法设计程序:
/** Return true if the card number is valid */
public static boolean isValid(long number)
// Get the result from Step 2:第二步
public static int sumOfDoubleEvenPlace(long number)
// Return this number if it is a single digit, otherwise,
// return the sum of the two digits:第一步
public static int getDigit(int number)
// Return sum of odd-place digits in number:第三步
public static int sumOfOddPlace(long number)
// Return true if the number d is a prefix for number:判断前缀
public static boolean prefixMatched(long number, int d)
// Return the number of digits in d:获取长度
public static int getSize(long d)
// Return the first k number of digits from number, If the 返回第一个k位数
// number of digits in number is less than k, return number:
public static long getPrefix(long number, int k)
可以改用String获取输入
下面是程序的运行示例:
Enter a credit card number as a long integer
4388576018410707
4388576018410707 is valid
Enter a credit card number as a long integer
4388576018402626
4388576018402626 is invalid
破题
- main方法:获取输入、将输入内容传递给isValid方法并接收结果、判断并输出结果
- isValid方法(被main方法调用):调用第二步第三步对应方法并获取返回值,两个数相加判断是否能被10整除
- sumOfDoubleEvenPlace和sumOfOddPlace两个方法:对偶数、对奇数进行不同的转换相加,由isValid方法调用
- getSize方法:判断长度,因为博主已经改用String类型接收,直接使用String的length()属性即可
- prefixMatched方法:判断前缀是否由4\5\6\37组成,由主方法调用
6.31代码
import java.util.Scanner;
public class Test6_31 {
public static void main(String[] args) {
// 获取输入
Scanner input = new Scanner(System.in);
System.out.print("Enter a credit card number as a long integer\n\t");
String str = input.next();
// 判断str长度是否达到标准
int length = getSize(str);
if (length < 13 || length > 16){
System.out.print(str + " is invalid")