Question

In: Computer Science

Having trouble with the Luhn algorithm for java. Everything works great except for when cthe number...

Having trouble with the Luhn algorithm for java. Everything works great except for when cthe number 5105105105105109 is entered. I'm sure there are other numbers that do this, but this returns check digit as 10 when it should come back as 0. Suggestions? here is the algorithm and then my current code without the prints because my error is in the math. I am not allowed to use break.

Another key part of the credit card number standard is the check digit. The last digit of every credit card number is determined by the previous 15 digits through a simple mathematical formula known the Luhn Algorithm. The Lhun Algorithm can be used to check if a credit card number has been corrupted in its transmission between the vendor reading the card, and the bank which has the account. It can also be used to check to see if a credit card number is valid before transmitting it to the bank.

The Luhn Algorithm is described at the link above, but the basic idea is:

  1. From the right-to-left, double the value of each digit that is in an even-numbered position (with the check-digit at position 1). If this doubling gives you a two-digit value for any of the numbers, then subtract 9 from the value (which is easier than adding the digits together but gets you the same result). Leave the odd-valued positions as is.
  2. Sum together all of the values except the check digit.
  3. Take the digit in the one's position of the sum. If the value of that digit is 0, then it stays as 0. If the value is greater than zero, subtract that value from 10. That value should be the check digit (note that the special case for 0 is required since "10" is not a single digit).

For example, suppose the card you want to validate is: 5457623898234113. In this case the check-digit is 3 and the remaining digits are the 15-digit account number. We can confirm that we likely have a good card number by validating the check digit as follows:

Position 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Original Value 5 4 5 7 6 2 3 8 9 8 2 3 4 1 1 3
Doubled value 10 10 12 6 18 4 8 2
Doubled-value adjusted 1 1 3 6 9 4 8 2
Sum of values = 67 1 4 1 7 3 2 6 8 9 8 4 3 8 1 2
Check digit is 3 (10 - 7 = 3)

You can read more about credit card numbers, as well as how the Luhn Algorithm is used in other areas of Computer Science, in this article from the Data Genetics blog (where the above example was taken from).

For this lab you will write a Java program that checks credit card strings to see if they are valid. Your program should first prompt the user to enter a string of numbers as a credit card number, or enter a blank line to quit the program. If the user doesn't quit, your program should ensure that this string is exactly 16 characters in length. If the user enters a string that is not 16 characters in length, your program should print an error message and ask again for a valid string. Your program should use the Luhn Algorithm above to compute what the check digit should be and then compare it to the actual value in the provided string and report whether the credit card number is valid or wrong. If it is wrong, your program should report what the correct check digit should be for the input value. Your program should keep asking for new values until the user enters a blank line to quit the program.

Create a new project named LuhnAlgorithm and a new Java program in that project folder named LuhnAlgorithm.java for this project. You can find a selection of valid-but-fake credit card numbers courtesy of PayPal at this link. Change the check digit on any of them to get an invalid number (note that your code should only use the 16 digit numbers and does not have to account for any of the card numbers that have any number of digits other than 16).

NOTE: You do NOT need to use arrays to solve this problem - this problem can be solved just with nested loops. Solutions that use an array where it isn't needed will be penalized in two ways: First, you're making the problem much harder than it needs to be, and second there will be a point deduction for use of an unnecessary array in the solution.

Sample Output: This is a sample transcript of what your program should do. Items in bold are user input and should not be put on the screen by your program.

Enter a credit card number (enter a blank line to quit): 5457623898234112
Check digit should be: 3
Check digit is: 2
Number is not valid.

Enter a credit card number (enter a blank line to quit): 5457623898234113
Check digit should be: 3
Check digit is: 3
Number is valid.

Enter a credit card number (enter a blank line to quit): 5555555555554
ERROR! Number MUST have exactly 16 digits.

Enter a credit card number (enter a blank line to quit): 5555555555554445
Check digit should be: 4
Check digit is: 5
Number is not valid.

Enter a credit card number (enter a blank line to quit): 
Goodbye!

import java.util.Scanner;

public class LuhnAlgorithm {

public static int Luhn(String credNum) {

int sum = 0;

for(int i = 15; i >= 0; i--) {

/* initializing i as 15, making sure the number is greater than 0, decrementing i */

if(i % 2 == 0) {

/* if int i is even */

int credDigit = 2*(credNum.charAt(i) - '0');

/*int credDigit is 2 times the number at the index listed */

if(credDigit > 9)

/* if the number doubled is in the double digits */

credDigit = ((credDigit % 10) - 9);

sum += credDigit;

/* subtract credDigit by 9 */

}

else

sum += (credNum.charAt(i) - '0');

/* Otherwise, add the number at the index listed to the sum */

}

sum -= (credNum.charAt(15) - '0');

return (10 - sum % 10);

/* returns the check digit */

}

Solutions

Expert Solution

/*package whatever //do not write package name here */

import java.io.*;
import java.util.*;
import java.lang.*;
public class LuhnAlgorithm{
    public static int Luhn(String credNum) {
int sum = 0;
for(int i = 15; i >= 0; i--) {
/* initializing i as 15, making sure the number is greater than 0, decrementing i */
if(i % 2 == 0) {
/* if int i is even */
int credDigit = 2*(credNum.charAt(i) - '0');
/*int credDigit is 2 times the number at the index listed */
if(credDigit > 9)
/* if the number doubled is in the double digits */
credDigit = ((credDigit % 10) - 9);
sum += credDigit;
/* subtract credDigit by 9 */
}
else
sum += (credNum.charAt(i) - '0');
/* Otherwise, add the number at the index listed to the sum */
}
sum -= (credNum.charAt(15) - '0');
return (10 - sum % 10);
/* returns the check digit */
}
   public static void main (String[] args) {
       Scanner sc=new Scanner(System.in);
       int l;
       String str;
       System.out.println("Enter a credit card number (enter a blank line to quit):");
        str=sc.nextLine();
       l=str.length();
        if(l!=16){
            System.out.println("ERROR! Number MUST have exactly 16 digits.");
            System.out.println("Enter a credit card number (enter a blank line to quit):");
            str=sc.nextLine();
            l=str.length();
        }
       if(str.length()==0){
            System.out.println("Goodbye!");
            System.exit(0);
       }
       char[] S = str.toCharArray();
        int result=Character.getNumericValue(S[15]);
       // LuhnAlgorithm s=new LuhnAlgorithm();
        int m=Luhn(str);
        if(result==m){
            System.out.println("Check digit should be:"+m);
            System.out.println("Check digit should be:"+result);
            System.out.println("Number is valid.");
        }
        else{
            System.out.println("Check digit should be:"+m);
            System.out.println("Check digit should be:"+result);
            System.out.println("Number is not valid.");
        }
   }
}


Related Solutions

Im in a java class and having trouble with assigning the seat to a specific number...
Im in a java class and having trouble with assigning the seat to a specific number from the array.. Below are the instructions I was given and then the code that I have already.   ITSE 2321 – OBJECT-ORIENTED PROGRAMMING JAVA Program 8 – Arrays and ArrayList A small airline has just purchased a computer for its new automated reservations system. You have been asked to develop the new system. You are to write an application to assign seats on flight...
Everything else works except the range, I only want the numbers entered to be in between...
Everything else works except the range, I only want the numbers entered to be in between 2-70 but I can enter 700 for some reason. How can I make the limit work? (This is in C#) namespace Prime_Numbers { class Program { static void Main(string[] args) { int limit; // Declare limit as an int as we do not need double. Console.WriteLine("*****************************\nPRIME NUMBERS UP TO 25\n*****************************"); Console.Write("Enter a limit to the prime numbers you want displayed: "); while (true) {...
Having some trouble with this Java Lab (Array.java) Objective: This lab is designed to create an...
Having some trouble with this Java Lab (Array.java) Objective: This lab is designed to create an array of variable length and insert unique numbers into it. The tasks in this lab include: Create and Initialize an integer array Create an add method to insert a unique number into the list Use the break command to exit a loop Create a toString method to display the elements of the array Task 1: Create a class called Array, which contains an integer...
Hello! I am having trouble starting this program in Java. the objective is as follows: "...
Hello! I am having trouble starting this program in Java. the objective is as follows: " I will include a text file with this assignment. It is a text version of this assignment. Write a program that will read the file line by line, and break each line into an array of words using the tokenize method in the String class. Count how many words are in the file and print out that number. " my question is, how do...
This is a Java program that I am having trouble making. 1- Search for the max...
This is a Java program that I am having trouble making. 1- Search for the max value in the linked list. 2- Search for the min value in the linked list. 3- Swap the node that has the min data value with the max one. (Note: Move the nodes to the new positions). 4- Add the min value and the max value and insert the new node with the calculated value before the last node. I already made a generic...
I am working on these study questions and am having trouble understanding how it all works...
I am working on these study questions and am having trouble understanding how it all works together. Any help would be greatly appreciated!! An all equity firm is expected to generate perpetual EBIT of $50 million per year forever. The corporate tax rate is 0% in a fantasy no tax world. The firm has an unlevered (asset or EV) Beta of 1.0. The risk-free rate is 5% and the market risk premium is 6%. The number of outstanding shares is...
(Java) Building a Doubly Linked List off of an interface I am having trouble with these...
(Java) Building a Doubly Linked List off of an interface I am having trouble with these two methods @Override public void add(T newEntry) { DoubleLinkedNode newNode = new DoubleLinkedNode(newEntry); if (!isEmpty()) { } if (isEmpty()) { first = newNode; last = newNode; } else { last.setNextNode(newNode); newNode.setPreviousNode(last); last = newNode; } // length++; numElements++; } @Override public void add(int newPosition, T newEntry) { DoubleLinkedNode newAdder = new DoubleLinkedNode(newEntry); if ((newPosition >= 0) && (newPosition <= numElements)) { numElements++; if (newPosition...
having trouble with loop, when I added saving and loading to my code, when adding new...
having trouble with loop, when I added saving and loading to my code, when adding new player, it continues to ask for new player class TeamClass: name = "" jersey = "" number = "" def __init__(self, name, jersey, number): self.name = name self.number = number self.jersey = jersey def set_name(self, name): self.name = name def set_jersey(self, jersey): self.jersey = jersey def set_number(self, number): self.number = number def get_name(self, name): return self.name def get_jersey(self, jersey): return self.jersey def get_number(self, number):...
The multi-merge sort algorithm (M&M sort) works like merge sort, except that instead of dividing the...
The multi-merge sort algorithm (M&M sort) works like merge sort, except that instead of dividing the array into 2 partitions, it divides the array into p partitions. It recursively sorts each of the p partitions and then merges the results doing a p-way merge (except, of course, for the base case of a singleton or empty array). (a) Write the recurrence for T(n) for M&M sort for the case where p is a constant. Then, give a closed-form solution to...
Having a problem with syntax error in Java: JAVA (Perfect Numbers) An integer number is said...
Having a problem with syntax error in Java: JAVA (Perfect Numbers) An integer number is said to be a perfect number if its factors, including 1 (but not the number itself), sum to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3. Write a method isPerfect that determines whether  parameter number is a perfect number. Use this method in an application that displays all the perfect numbers between 1 and and integer entered...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT