首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何实现个人号码校验6位数的Luhn算法?

如何实现个人号码校验6位数的Luhn算法?
EN

Stack Overflow用户
提问于 2018-01-23 23:57:07
回答 1查看 97关注 0票数 0

我是Java的初学者,正在试图弄清楚如何在我找到的这个银行系统中实现luhn算法。

是否可以使用数组列表来添加帐户?

类银行:

代码语言:javascript
复制
public class Bank {    
private String bank_name;   // Name of the Bank.
private Scanner input;      // private scanner to retrieve
                            // user input
// Some Booleans to control program flow
private boolean bContinue = true;
private boolean bAcc = true; 
// constructors
Bank()  {}
Bank(String b_name)
{
    // Name of Bank is set in constructor
    bank_name = b_name;    }
int processClients()
{
    System.out.println("\t" + bank_name.toUpperCase());
    System.out.println("==========================================");        
    // System has a possible 32 accounts to be used 
    Account[] pAccounts = new Account[32];        
    // In the following loop we initialise the accounts all to null 
    // which makes it easier to find a terminating account when     
    // looping later on in the code - as we can check if an account 
    // is null and subsequently know that no accounts in the array  
    // after such point have been initialised.                    
    int counter = 0;
    while( counter < 32)
    {
        pAccounts[counter] = null;
        counter++;
    }
    // Some variables for temporarily storing       
    // account credentials in before setting up account 
    String tmp_name_f, tmp_name_l;
    double tmp_bal;
    long tmp_num;        
    // initalise scanner here to begin gathering user input 
    input = new Scanner(System.in);        
     // Below we will being adding accounts to the database / array 
    // this loop continues till a terminating condition is met.    
    System.out.println("Begin Adding 
Accounts\n==========================================");
    for( int i = 0; i < pAccounts.length; i++)
    {
        System.out.println("Account Holders First Name :: ");
        tmp_name_f = input.next();
        System.out.println("Account Holders Last Name :: ");
        tmp_name_l = input.next();
        System.out.println("BSB - AccountNumber :: ");
        tmp_num = input.nextLong();
        System.out.println("Opening Balance :: ");
        tmp_bal = input.nextDouble(); 
        // Store Information in Account Object Array by
        // initialising accounts as we precede          
        pAccounts[i] = new Account(new Client( tmp_name_f, tmp_name_l  ), 
tmp_bal, tmp_num); 
        // Check if user wishes to add another account, if "N" 
        // is entered, we break out of account creation loop   
        System.out.println("Add Another Account ? (Y / N) :: ");
        if(input.next().equals("N"))
            break;
    }        
//The boolean here, indicates user wishes to continue utilising the 
Banking System 
    while (bContinue)
    {
        int acc;    // account index to access.
        System.out.println("\nSelect Account - 
Index\n==========================================");
        for ( int k = 0; k < pAccounts.length; k++)
        {
            // earlier we initialised accounts to null                                     
            // this check is just to ensure the account is valid and has 
been instantiated 
            if(pAccounts[k] != null)
            System.out.println(k + " ) " + pAccounts[k].get_name() + 
            "\nAccount Number : " + pAccounts[k].get_account_number() );
        }
        acc = input.nextInt(); 
        // This Boolean indicates the user wishes to continue on with the 
same account 
        while (bAcc)
        {
            // This could be done in a switch statement, however i prefer 
if's.
            // basically, we select which member function of Account to call  
            // for the account designated in the code above, each selection  
            // either fetches or changes values of a specific account 
denoted 
            // by index.                                                     
            System.out.println("\nChoose Function\n1 ) Deposit\n2 ) 
Withdraw\n3 ) Balance Enquiry\n4 ) Change Contact Details");
            int sel = input.nextInt();
            if ( sel == 1)
            {
                System.out.println("Enter Amount to Deposit = $ ");                
                pAccounts[acc].deposit_funds(input.nextDouble() );
            }
            else if ( sel == 2)
            {
                System.out.println("Enter Amount To Withdraw = $ ");
                if( pAccounts[acc].withdraw_funds(input.nextDouble() ) == 
-1)
                {
                    System.out.println("Insufficient Funds");
                }
                else
                    System.out.println("Take your Funds");
            }
            else if ( sel == 3)
            {
                System.out.println("Balance = $ " + String.format("%.2f", 
pAccounts[acc].get_balance()) );
            }
            else if (sel == 4)
            {
                System.out.println("Current Contact Number : " + 
pAccounts[acc].getClient().getPhoneNumber() );
                /*
                 * You could in here also have an option to change contact 
details
                 * a call such as
                 * pAccounts[acc].getClient().set_or_change_phoneContact( 
55202020 )
                 * would do this
                 */                }
            else
                System.out.println("Invalid Selection"); 

            // Check if user would like to change accounts or continue with 
current account
            System.out.println("Continue With This Account\n1 ) Yes\n2 ) 
No");
            if( input.nextInt() == 1)
                    bAcc = true;
            else bAcc = false;
        }
        bAcc = true;            
        // Check if to continue on with banking system.
        System.out.println("Would You Like To Continue\n1 ) Yes\n2 ) No");
        if (input.nextInt() == 1) bContinue = true;
        else
            return 0;   // we return early and essentially exit program        
    }
    return 0;
}    
public static void main(String[] args)
{
   Bank myBank = new Bank("National Australia Bank");
   System.exit( myBank.processClients() );
}
}

类Client:

是否可以在这里添加personal-number(六位数),并使用set和get方法来执行Luhn算法检查?

代码语言:javascript
复制
public class Client { 
private String name_first, name_last;
private long phone_contact;

// default constructor
Client()    {}

// Overload Constructor    
Client(String name_f, String name_lst)
{
    name_first = name_f;
    name_last = name_lst;

    // this is here for example only        
    // it is up to you to implement functions        
    // to set / change this value through banking
    // program. A basic function is included below

    phone_contact = 999999;
} 

// method to return full name
String getName()
{
    return (name_first + " " + name_last);
      }
void changeFirstName(String n_new)
{
    name_first = n_new;
}
void changeLastName(String n_new)
{
    name_last = n_new;
}
void change_phone_number(long p_number)
{

    phone_contact = p_number;
}
long getPhoneNumber()
{
    return phone_contact;
}   
}

班级帐户:

代码语言:javascript
复制
public class Account {    
// variables contained within class account 

// accessible only via methods/functions as 

// they are private and subsequently can    

// only be changed via member functions.    

private Client person;            // account holders client

private double balance;           // current account balance

private long account_number;      // account number

// Constuctor for Objects of type account //

Account( Client c_client, double c_balance, long c_num)
{
    person = c_client;
    balance = c_balance;
    account_number = c_num;
}
// Function to deposit funds into an account //

public void deposit_funds( double p_amount)
{
    balance += p_amount;
}
// function to withdraw funds from an account //
    // checks to see whether funds are available. //

public int withdraw_funds( double p_amount)
{
    // check if enough funds
    if ( p_amount > balance )
        return -1;
    else
        balance -= p_amount;
    return 0;
} 

// returns account balance 
public double get_balance()
{
    return balance;
}

// returns account holders name
public String get_name()
{

    // Access our client object (person)
    // then access getName() function
    // of Client class
    return person.getName();
}
// returns account number //
public long get_account_number()
{
    return account_number;
}
public Client getClient()
{
    return person;
}
}
EN

回答 1

Stack Overflow用户

发布于 2018-01-24 02:34:57

代码语言:javascript
复制
static int[] digits (int number){
    String numberString;
    try {
         numberString = Integer.toString(number);
    }
    catch (Exception e){
        return null;
    }
    int[] n=new int[numberString.length()];

    for (int i = 0; i < n.length; i++)
    {
        n[i] = numberString.charAt(i) - '0';
    }
    return n;
}
static boolean isLuhn(int number){
   int[] numberArry= digits(number);
   if(numberArry==null||numberArry.length!=6){
       return false;
   }

   int[] doubleEveryOther=new int[numberArry.length-1];
   for(int i=0;i<(numberArry.length-1);i++){
       if(i%2==1){
         int[] sumArry = digits(numberArry[i]*2);
         int sum=0;
         for(int t=0;t<sumArry.length;t++){
             sum+=sumArry[t];
         }
         doubleEveryOther[i]=sum;

       }else {
           doubleEveryOther[i]=numberArry[i];
       }
    }
    int sumAll=0;
    for(int i=0;i<doubleEveryOther.length;i++){
        sumAll+=doubleEveryOther[i];
    }
    if((sumAll*9)%10!=numberArry[numberArry.length-1]){
        return false;
    }
    return true;
}
public static void main(String[] args){
    System.out.println(isLuhn(123410));
    System.out.println(isLuhn(123411));
    System.out.println(isLuhn(123412));
    System.out.println(isLuhn(123413));
    System.out.println(isLuhn(123414));
    System.out.println(isLuhn(123415));
    System.out.println(isLuhn(123416));
    System.out.println(isLuhn(123417));
    System.out.println(isLuhn(123418));
    System.out.println(isLuhn(123419));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48405892

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档