Untitled
unknown
java
2 years ago
3.4 kB
5
Indexable
package Labs.Assignment6; import java.util.*; public class QuestionSixPointThrityOne { public static int sumOfOddPlace(ArrayList<Integer> cardNumberList) { /* * 1. Take in the arrayList that contains the digits of the card number * and iterate through it * 2. sum up all the odd place digits * 3. start at 15 and subtract two until count is less than 0 than break * 4. return the sum */ int sum = 0; int count =cardNumberList.size()-1; for(int i = 0; i< (cardNumberList.size());i++) { int product = cardNumberList.get(count); sum = sum + product; count-=2; if(count <0) { break; } } return sum; } public static ArrayList<Integer> cardNumList(long cardNumber) { /* * 1.Take in the long number and convert it to a string * 2. convert the string into an array of characters * 3. iterate through the array and convert every value into and integer than add it to an * array list * 4.return the arraylist */ ArrayList<Integer> cardNumberList = new ArrayList<>(); String cardNumberString = Long.toString(cardNumber); char[] digits = cardNumberString.toCharArray(); for(int i = 0; i<(digits.length); i++) { int num = Character.getNumericValue(digits[i]); cardNumberList.add(num); } return cardNumberList; } public static int sumFunctionForTwoPlaces(int product) { /* * 1.take */ int remainder =0; int sum = 0; while(product > 0) { remainder =product%10; sum += remainder; product = product / 10; } return sum; } public static int sumOfEvenPlace(ArrayList<Integer> cardNumberList) {/* * 1.take in the arrayList of the digits of the card * 2.iterate throught the arrayList starting at 14 and change the index by 2 every time * 3.multiply the digit by 2 then check the length if it * 4.if the lenght of the product is greater than 1, * then send it to the sumFunctionForTwoPlaces method and add the return value to the sum * 5.if it is equal to 1 add the product to the sum * 6.check if the count is less than zeor if it is break if not continue * 7.return the sum value */ int sum =0; int count =cardNumberList.size()-2; for(int i = 0; i< (cardNumberList.size());i++) { int product = cardNumberList.get(count) * 2; int length = Integer.toString(product).length(); if(length>1) { int sumOfProduct = sumFunctionForTwoPlaces(product); sum = sum + sumOfProduct; } if(length ==1) { sum = sum + product; } count-=2; if(count <0) { break; } } return sum; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int stepOneSum; int stepTwoSum; System.out.println("Enter a credit card number as a long integer:"); long cardNumber = scanner.nextLong(); ArrayList<Integer> cardNumberList = cardNumList(cardNumber); stepOneSum = sumOfEvenPlace(cardNumberList); stepTwoSum = sumOfOddPlace(cardNumberList); int finalSum = stepOneSum + stepTwoSum; if(finalSum%10 == 0) { System.out.printf("%d is valid",cardNumber); } if(finalSum%10 != 0) { System.out.printf("%d is invalid",cardNumber); } scanner.close(); } }
Editor is loading...