0

I am trying to take a user input credit card number and put it into a Luhn algorithm. When i run the code I get a conversion='i' error. I am also getting a two digit number when calling 'check.'

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter a credit card number (enter a blank line to quit): ");
    String ccNumber=keyboard.nextLine();
    long length2 = String.valueOf(ccNumber).length();

    int length = toIntExact(length2);

    if (length == 0) {
        System.out.print("Goodbye!");
        System.exit(0);
    }
    if (length  != 16) {
        System.out.println("ERROR! Number MUST have exactly 16 digits");
        System.exit(0);
    }
    int check = ccNumber.charAt(15);

    int sum = 0;
    boolean alternate = false;
    int i = length-1;
    while (i >= 0)
    {
            int n = Integer.parseInt(ccNumber.substring(i, i + 1));
            if (alternate)
            {
                    n *= 2;
                    if (n > 9)
                    {
                            n = (n % 10) + 1;
                    }
            }
            sum += n;
            alternate = !alternate;
            i--;
    }
    if (sum % 10 == 0) {
        System.out.printf("Check number should be: %i",check);
        System.out.printf("Number is valid\n");
    }
    else {
        System.out.printf("Check number should be: %s", check+"\n");
        System.out.printf("Number is NOT valid\n");
    }
    }
}
Joshua
  • 3
  • 1
  • Note that `String.charAt()` returns a character. You will need to convert ASCII to an int if you want the value (e.g., the char `1` has the decimal value 49, not 1). – Mike Harris Sep 29 '18 at 18:43
  • *I get a conversion='i' error*: what does that mean? What is the complete and exact error? *I am also getting a two digit number when calling 'check.'*: there is no check method in the code you posted. – JB Nizet Sep 29 '18 at 18:51
  • Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'i' at java.util.Formatter$FormatSpecifier.conversion(Unknown Source) at java.util.Formatter$FormatSpecifier.(Unknown Source) at java.util.Formatter.parse(Unknown Source) at java.util.Formatter.format(Unknown Source) at java.io.PrintStream.format(Unknown Source) at java.io.PrintStream.printf(Unknown Source) at osu.cse1223.Project06.main(Project06.java:44) That is the full error – Joshua Sep 29 '18 at 19:26

1 Answers1

0

Replace this

int check = ccNumber.charAt(15);

with this

int check = Character.getNumericValue(ccNumber.charAt(15));

And

System.out.printf("Check number should be: %i",check);

with

System.out.printf("Check number should be: %d\n",check);

And

System.out.printf("Check number should be: %s", check+"\n");

with

System.out.printf("Check number should be: %d\n", check);
RaffleBuffle
  • 5,396
  • 1
  • 9
  • 16