Question

Design and implement an ADT in JAVA that represents a credit card. it should include the...

Design and implement an ADT in JAVA that represents a credit card. it should include the customer name, the account number, credit limit, the reward points and the account balance. The initialization operation should set the data to client-supplied values. The credit limit will be initializes to $5000 and reward points to 0. Next, write a method to validate the card number using the Luhn Algorithm and implement it as a part of initialization process. If the number is invalid, throw a custom exception with the message "Invalid Account Number".

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem including test code (Test.java). Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

//CreditCard.java

public class CreditCard {

    // attributes

    private String customerName;

    private String accountNumber;

    private double creditLimit;

    private int rewardPoints;

    private double accountBalance;

    // constructor to initialize all fields

    public CreditCard(String customerName, String accountNumber,

             double creditLimit, int rewardPoints, double accountBalance) {

         // using isValid method, validating account number, if it is not valid,

         // throwing a CreditCardException

         if (!isValid(accountNumber)) {

             throw new CreditCardException("Invalid Account Number");

         }

         // if credit limit, or account balance is negative, throwing exception

         if (creditLimit < 0) {

             throw new CreditCardException("Invalid Credit Limit");

         }

         if (accountBalance < 0) {

             throw new CreditCardException("Invalid Account Balance");

         }

         // if reward points is negative, making it 0 (not throwing exception as

         // this is not very important)

         if (rewardPoints < 0) {

             rewardPoints = 0;

         }

         // assigning validated values

         this.customerName = customerName;

         this.accountNumber = accountNumber;

         this.creditLimit = creditLimit;

         this.rewardPoints = rewardPoints;

         this.accountBalance = accountBalance;

    }

    // private helper method to check if cardNum is a valid credit card number

    // using Luhn's algorithm

    private boolean isValid(String cardNum) {

         int sum = 0; // checksum

         // flag variable which will be true for every second digit from the rear

         // and false for any other digits

         boolean second = false;

         // looping through each characters on the card in reverse order

         for (int i = cardNum.length() - 1; i >= 0; i--) {

             // if current character is not a digit, returning false

             if (!Character.isDigit(cardNum.charAt(i))) {

                 return false;

             }

             // converting char to digit

             int digit = Character.digit(cardNum.charAt(i), 10);

             // if this is not a second digit, simply adding to sum

             if (!second) {

                 // adding digit to sum

                 sum += digit;

             } else {// otherwise

                 // doubling digit

                 int doubled = digit * 2;

                 // extracting last and first digits

                 int lastDigit = doubled % 10;

                 int firstDigit = doubled / 10;

                 // adding to sum

                 sum += lastDigit + firstDigit;

             }

             // inversing the value of second

             second = !second;

         }

         // checking if checksum ends with 0

         if (sum % 10 == 0) {

             // valid

             return true;

         } else {

             // invalid

             return false;

         }

    }

    // getters and setters

    public double getCreditLimit() {

         return creditLimit;

    }

    public void setCreditLimit(double creditLimit) {

         if (creditLimit > 0)

             this.creditLimit = creditLimit;

    }

    public int getRewardPoints() {

         return rewardPoints;

    }

    public void setRewardPoints(int rewardPoints) {

         if (rewardPoints > 0)

             this.rewardPoints = rewardPoints;

    }

    public double getAccountBalance() {

         return accountBalance;

    }

    public void setAccountBalance(double accountBalance) {

         if (accountBalance > 0)

             this.accountBalance = accountBalance;

    }

    public String getCustomerName() {

         return customerName;

    }

    public String getAccountNumber() {

         return accountNumber;

    }

    // returns a String containing field values

    public String toString() {

         return "customerName=" + customerName + ", accountNumber="

                 + accountNumber + ", creditLimit=" + creditLimit

                 + ", rewardPoints=" + rewardPoints + ", accountBalance="

                 + accountBalance;

    }

}

// CreditCardException class to represent a custom exception

class CreditCardException extends RuntimeException {

    public CreditCardException(String msg) {

         super(msg);

    }

}

//Test.java (tester program)

public class Test {

    public static void main(String[] args) {

         // inside a try catch block, creating and displaying two Cards

         try {

             // 12345678903555 is a valid credit card number

             CreditCard card1 = new CreditCard("Oliver", "745111417143",

                      20000, 100, 15000);

             // displaying the card details

             System.out.println("Card1: " + card1);

             // 745111417144 is NOT a valid credit card number, hence will

             // throw exception

             CreditCard card2 = new CreditCard("John", "745111417144", 42000,

                      0, 10000);

             System.out.println("Card2: " + card2);

         } catch (CreditCardException ex) {

             System.out.println("Error: " + ex.getMessage());

         }

    }

}

/*OUTPUT*/

Card1: customerName=Oliver, accountNumber=745111417143, creditLimit=20000.0, rewardPoints=100, accountBalance=15000.0

Error: Invalid Account Number

Add a comment
Know the answer?
Add Answer to:
Design and implement an ADT in JAVA that represents a credit card. it should include the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Needs Help In Java Programming language Exceptional Cars Purpose To review interfaces and exception usage. Directions...

    Needs Help In Java Programming language Exceptional Cars Purpose To review interfaces and exception usage. Directions Your task is to write a class called Car. Your class should have the following fields and methods: private int position private boolean headlightsOn public Car() - a constructor which initializes position to 0 and headlightsOn to false public Car(int position) - a constructor which initializes position to the passed in value and headlightsOn to false, and it should throw a NegativeNumberException with a...

  • Stacks and Java 1. Using Java design and implement a stack on an array. Implement the...

    Stacks and Java 1. Using Java design and implement a stack on an array. Implement the following operations: push, pop, top, size, isEmpty. Make sure that your program checks whether the stack is full in the push operation, and whether the stack is empty in the pop operation. None of the built-in classes/methods/functions of Java can be used and must be user implemented. Practical application 1: Arithmetic operations. (a) Design an algorithm that takes a string, which represents an arithmetic...

  • Banks issue credit cards with 16 digit numbers. If you've never thought about it before you...

    Banks issue credit cards with 16 digit numbers. If you've never thought about it before you may not realize it, but there are specific rules for what those numbers can be. For example, the first few digits of the number tell you what kind of card it is - all Visa cards start with 4, MasterCard numbers start with 51 through 55, American Express starts with 34 or 37, etc. Automated systems can use this number to tell which company...

  • Java Please - Design and implement a class Triangle. A constructor should accept the lengths of...

    Java Please - Design and implement a class Triangle. A constructor should accept the lengths of a triangle’s 3 sides (as integers) and verify that the sum of any 2 sides is greater than the 3rd(i.e., that the 3 sides satisfy the triangle inequality). The constructor should mark the triangle as valid or invalid; do not throw an exception. Provide get and set methods for the 3 sides, and recheck for validity in the set methods. Provide a toString method...

  • Java programming for ticket price calculator.  It should ask the user if they would like to process...

    Java programming for ticket price calculator.  It should ask the user if they would like to process another ticket order. They should indicate their selection with a Y or N. If they indicate yes, then it should repeat the entire program with the exception of the welcome screen. If they indicate no, it should show the final thank you message and end the program. If they indicate an invalid answer, it should display an error and re-prompt them for a Y...

  • Instructions Using the BCException.java and the BankCustomer.java from the first part of the assignment you will...

    Instructions Using the BCException.java and the BankCustomer.java from the first part of the assignment you will implement a driver class called Bank.java to manipulate an ArrayList of BankCustomer objects. Your code should read bank customers’ information from the user. It will then create a bank customer objects and add them to an arraylist in a sorted fashion (sorted by account number). The arraylist should be sorted in ascending order at all times. The arraylist should not contain null objects at...

  • Hello Guys. I need help with this its in java In this project you will implement...

    Hello Guys. I need help with this its in java In this project you will implement a Java program that will print several shapes and patterns according to uses input. This program will allow the use to select the type (say, rectangle, triangle, or diamond), the size and the fill character for a shape. All operations will be performed based on the user input which will respond to a dynamic menu that will be presented. Specifically, the menu will guide...

  • Please write c++ (windows) in simple way and show all the steps with the required output

    please write c++ (windows) in simple way and show all the steps with the required output Write a C++ program that simulates the operation of a simple online banking system The program starts by displaying its main menu as shown in Figure1 splay Account nformatson verity Your credit Card elect vour choice Figure 1 Main menu of the program The menu is composed of the following choices 1. When choice 1 is selected (Display Account information), the program should display...

  • Design and implement a class Q that uses Q.java as a code base. The queue ADT...

    Design and implement a class Q that uses Q.java as a code base. The queue ADT must use class LinkedList from Oracle's Java class library and its underlying data structure (i.e. every Q object has-a (contains) class LinkedList object. class Q is not allowed to extend class LinkedList. The methods that are to be implemented are documented in Q.java. Method comment blocks are used to document the functionality of the class Q instance methods. The output of your program must...

  • I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT w...

    I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT with the implementation of your choice (Array or Link), it should not make a difference 2.Read two “integer” numbers from the user. Hint: You don’t need to use an int type when you read, it may be easier to parse the input...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT