Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an array with two possible input values

Tags:

java

arrays

I am working on a Luhn's test problem and I would like to build the program using a 1-D array. I have initialized an array with 16 digits but I would like to be able to initialize the array depending on how many digits the user enters.

   //create scanner object
   Scanner input = new Scanner(System.in);

   //declare variable
   long [] cc_num = new long[16];

   //get input
   System.out.print("Enter 15 or 16-digit credit card number: ");
   //long cc_num = input.nextLong();
   for (int i = 0; i < cc_num.length; i++) {
       cc_num[i] = input.nextLong();
    }

How can I initialize an array depending on the length of the input (15 or 16 is requested)

like image 811
Parth Avatar asked Dec 14 '22 13:12

Parth


1 Answers

I agree to what Elliott has proposed. But I'm curious as to why you are using long data type. If you were to hold credit card into a variable, long would be the solution. 16 digit perfectly fits into long. Here is what I would use

System.out.print("Enter 15 or 16-digit credit card number: ");
String cardStr = input.nextLine();
int [] cc_num = new int[cardStr.length()];

more better way

System.out.print("Enter 15 or 16-digit credit card number: ");
String cardStr = input.nextLine();
long cc_num = Long.parseLong(cardStr);

best way

System.out.print("Enter 15 or 16-digit credit card number: ");
String cardStr = input.nextLine();
//store as string itself, so that leading 0's are preserved
//it really makes more sense because no arithemtic operations are performed on cc numbers
like image 101
JavaHopper Avatar answered Dec 17 '22 03:12

JavaHopper