Java黑皮书课后题第6章:**6.31(金融应用:信用卡号的合法性验证)和**6.32 编写程序,提示用户输入一个long型整数的信用卡号码,显示这个数字是合法的还是非法的

该博客介绍了如何使用Java编程验证信用卡号的合法性,包括Visa、Master、American Express和Discover卡。通过Hans Luhn提出的算法,从右到左处理偶数位和奇数位数字,并检查总和是否能被10整除。博客提供了多个辅助方法,如`isValid`、`sumOfDoubleEvenPlace`等,并展示了一个运行示例。
摘要由CSDN通过智能技术生成

6.31(金融应用:信用卡号的合法性验证)编写程序,提示用户输入一个long型整数的信用卡号码,显示这个数字是合法的还是非法的

6.31题目

题目描述

6.31(金融应用:信用卡号的合法性验证)信用卡号遵循某种模式。一个信用卡号必须是13到16位的整数,它的开头必须是:

  • 4,指Visa卡
  • 5,指Master卡
  • 37,指American Express卡
  • 6,指Discover卡

1954年,IBM的Hans Luhn提出一种算法,用于验证信用卡号的有效性。这个算法在确定输入的卡号是否正确,或者这张信用卡是否被扫描仪正确扫描方面是非常有用的。遵循这个方法……(假设卡号为4388576018402626):

  1. 从右往左偶数位数字翻倍。(如果翻倍之后是两位数则将两位加在一起得到一位数)
  2. 将第一步得到的所有一位数相加
  3. 将从右往左的奇数位相加
  4. 2、3步结果相加
  5. 如果第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

破题

  1. main方法:获取输入、将输入内容传递给isValid方法并接收结果、判断并输出结果
  2. isValid方法(被main方法调用):调用第二步第三步对应方法并获取返回值,两个数相加判断是否能被10整除
  3. sumOfDoubleEvenPlace和sumOfOddPlace两个方法:对偶数、对奇数进行不同的转换相加,由isValid方法调用
  4. getSize方法:判断长度,因为博主已经改用String类型接收,直接使用String的length()属性即可
  5. 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")
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值