-2

okay so to the preface the situation. I have been given an assignment with various tasks. So far I have created a Canteen Account(which will be shown below), a main menu class, and now I have to make another class which inherits from Canteen Account, called StaffAccount. A StaffAccount object should contain the following additional property :

discountRate - the rate (percentage) discount applied to all purchases

A StaffAccount object should contain the following additional methods:

(i) StaffAccount (String newId, String newName, double discountRate)

A constructor method to initialise the StaffAccount object’s properties via the three parameters.

In the staff account I am having issues with a method called PayForMeal(which is an overridden method) which in the assignment brief has the purpose of:

A method to record the cost of a meal. The balance on a StaffAccount object should be amended to reflect discount on the cost of a meal (if the cost does not exceed available balance).

If the cost exceeds the balance then an Exception will be thrown to warn the customer they must topUp their balance – if the customer is within their credit limit a negative value will be recorded in the balance and the status of the account changed to show that the customer is using credit. No discount should be applied if the customer is using credit.

So my issue is, how do I make a staff account using the constructor given to me, and then use the payForMeal overridden method to apply a discount to the amount a meal costs, then take the discounted amount away from a balance which is not there because it is not in the constructor for the StaffAccount, but it is in the constructor for the CanteenAccount. The classes are below, i just want to know if this is possible or am I being dumb

//////CANTEEN ACCOUNT \\\\\\\\

public class CanteenAcc 
{
        private String customerId; 
        private String name;
        private double balance;
        private static double minTopup = 2.00;
        private String status;
        private static double creditLimit = 5.00; 
        private static int transCount;

       /**
        * Constructor to create a Canteen account object using three parameters 
        * @param newId - String
        * @param newName - String
        * @param newBalance - Double
        */
       public CanteenAcc(String newId, String newName, double newBalance)
        { 
            this.customerId = newId;
            this.name = newName; 
            this.balance = newBalance;
        }
        public CanteenAcc(String newId, String newName)
        {
            this.customerId = newId;
            this.name = newName; 
        }

        //BEFORE EVERY METHOD AND CLASS YOU SHOULD HAVE JAVADOC COMMENTS.
        public void topUp(double depositAmount)
        {
            if(depositAmount > 0)
            {
                this.balance += depositAmount;
                this.status = "Valid";
            }else
            {
                this.status = "Invalid";

            }

        }  

         public void payForMeal(double amount) throws Exception
         {
            if(balance - amount < 0 && amount - balance <= creditLimit)
            {
                this.status = "Using Credit"; 
                double newBalance = balance - amount;
                balance = newBalance; 

                throw new Exception("\n\n-----------------------------\n"  
                        + "You must top-up your balance\n" 
                        + "Your new balance is: "+ balance + " GBP" +"\n" 
                        + "You are: " + status + "\n" 
                        + "-----------------------------\n");
            }
            else if(amount > creditLimit && balance < amount)
            {
                  throw new Exception("\n\n------------------------------\n"  
                        + "Cost exceeds the credit limit."
                          + "\n------------------------------\n");
            }
            else
            {   
                double newBalance = balance - amount;
                balance = newBalance; 
                transCount++;    
            }   
         }

       public String displayAccountDetails()  
       {
            StringBuilder ad = new StringBuilder(); 
            ad.append("------------------------\n");
            ad.append("****Account Details****\n");
            ad.append("------------------------\n");
            ad.append("\n");
            ad.append("****Customer ID****: \n" + customerId + "\n");
            ad.append("\n");
            ad.append("****Name****: \n" + name + "\n"); 
            ad.append("------------------------\n");
            ad.append("\n");
            return ad.toString();
       }

       public String getStatistics()
       {
            StringBuilder as = new StringBuilder();
            as.append("------------------------\n");
            as.append("    CANTEEN ACCOUNT    \n");
            as.append("------------------------\n");
            as.append("\n");
            as.append("****Transaction Count****\n");
            as.append(transCount + "\n");
            as.append("\n");
            as.append("****Account Balance****\n");
            as.append(balance + "\n");
            as.append("\n");
            as.append("***Account Status****\n");
            as.append(status + "\n");
            as.append("------------------------\n");
            return as.toString();
       }


       public double getBalance()
       {
          return balance;
       }

       public double getCreditLimt()
       {
           return creditLimit; 
       }

       public double getMinTopup() 
       {
           return minTopup;
       }

       public String getStatus()
       {
           return status; 
       }

       public static void updateCreditLimit(double newLimit)
       {
           creditLimit = newLimit; 

       }

       public static void updateMinTopup(double newTopup)
       {
            minTopup = newTopup; 
       }


}

////////MAIN METHOD////////////////////////

public class Test 
{
    public static void main(String[] args) {


      String menuItems[] = {"1. Top up account ", "2. Pay for meal ", "3. Display Account Status",
                            "4. Display Account Balance ", "5. Display Account Details ", 
                            "6. Update credit limit ", "7. Update Minimum top-up ", "8. Exit program"}; 

      Menu myMenu = new Menu("Holiday Account", menuItems) ;
                int choice;
                Scanner keyb = new Scanner(System.in);
                                choice = myMenu.getChoice() ;

                do{
                choice = myMenu.getChoice();    
                //CanteenAcc Employee = new CanteenAcc("A01PL", "Patrick", 2);  
                CanteenAcc Employee2 = new StaffAccount("blah", "blah", 0.25);



                switch (choice)
                                {
                        case 1 : System.out.println("How much would you like to top-up: ");
                                        double deposit = keyb.nextDouble(); 
                                        Employee2.topUp(deposit);
                                        System.out.println("Your balance is: £" + Employee2.getBalance());
                                                                                break ;

                        case 2:         System.out.println("Input how much your meal costs: ");
                        try             {
                                        double amount = keyb.nextDouble();
                                        Employee2.payForMeal(amount);


                                        System.out.println("Your meal cost: " + amount);
                                        } catch(Exception ex)
                                        {
                                            System.out.println(ex.toString());
                                        }
                                        System.out.println("Your balance is: £" + Employee2.getBalance());
                                                                                break ;

                        case 3:         System.out.println(Employee2.getStatus());         
                                        break; 

                        case 4:         System.out.println("£" + Employee2.getBalance());
                                        break;

                        case 5:         System.out.println(Employee.displayAccountDetails());
                                        break;

                        case 6:         System.out.println("What amount would you like the new limit to be: ");
                                        double newLimit = keyb.nextDouble();
                                        CanteenAcc.updateCreditLimit(newLimit);
                                        System.out.println("The new credit limit is: " + newLimit);

                        case 7:         System.out.println("What amount would you like the new limit to be: ");
                                        double newMinTopup = keyb.nextDouble();
                                        CanteenAcc.updateMinTopup(newMinTopup);   
                                        System.out.println("The new minimum topUp is: " + newMinTopup);

                        case 8:         System.exit(0);                 
                                }

             }//End DoWhile
             while(choice != 8);   



    }

}

////STAFF ACCOUNT///////

public class StaffAccount extends CanteenAcc 
{

    private double discountRate; 

    public StaffAccount(String newId, String newName, double discountRate)
    {
       super (newId, newName); 

       this.discountRate = 0.25;
       balance = 0;


    }   

     public void setDiscountRate(double rate)
     {
         discountRate = rate; 
     }

     public double getDiscountRate()
     {
         return discountRate; 
     }

   public void payForMeal(double amount) throws Exception
         {

            amount = amount/discountRate; 
              super.payForMeal(amount);
        }

}
paulsm4
  • 114,292
  • 17
  • 138
  • 190

1 Answers1

0

OK:

  1. You've got a CanteenAcc: good. You've also got a StaffAccount that inherits from CanteenAcc. Also good.

  2. You should annotate StaffAccount.payForMeal() with @Override: When do you use Java's @Override annotation and why?

  3. Your variable names should all start with lower case, e.g. CanteenAcc employee2 = new StaffAccount("blah", "blah", 0.25);.

  4. updateCreditLimit() and updateMinTopup() should NOT be static (because each different object might have a different value): Java: when to use static methods

... Finally ...

  1. With CanteenAcc employee = new CanteenAcc("A01PL", "Patrick", 2);, then employee.payForMeal() will have the "CanteenAcc" behavior.

  2. With CanteenAcc employee2 = new StaffAccount("blah", "blah", 0.25);, then employee2.payForMeal() will have the "StaffAccount" behavior.

Q: So what's the problem? Does that help clarify ... or does it just confuse things further?


There are a number of things "wrong" with the code you posted. I hope you have an IDE, and step through the debugger with sample test values.

But to your original question:

  1. You're on the right track.

  2. There are a couple of "minor" issues I noted above.

  3. I'm not sure why you're worried about "constructors". The way object oriented languages (like Java) work - if you define the right base classes, and appropriately "specialize" behavior in subclasses, then - through the magic of "inheritence" - everything "just works".

  4. I modified your code slightly, and wrote a different "test driver". Here is the code, and the output:

StaffAccount.java

package com.example;

public class StaffAccount extends CanteenAccount {
    private double discountRate;

    public StaffAccount(String newId, String newName, double discountRate) {
        super(newId, newName);
        this.discountRate = discountRate;  // Set this to "discountRate", instead of hard-coding 0.25
        // You'll note that "balance" is implicitly set to "0.0" in the base class
    }

    public void setDiscountRate(double rate) {
        discountRate = rate;
    }

    public double getDiscountRate() {
        return discountRate;
    }

    @Override
    public void payForMeal(double amount) throws Exception {
        amount = amount / discountRate;
        super.payForMeal(amount);
    }
}

TestAccount.java

package com.example;

/**
 * Test driver
 * In a "real" application, I would implement these as a suite of JUnit tests
 */
public class TestAccount {

    private static void buyAMeal (CanteenAccount person, double cost) {
        try {
            person.payForMeal(cost);            
        } catch (Exception e) {
            System.out.println ("ERROR: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        System.out.println (">>Creating employee (\"CanteenAccount\" and employee2 (\"StaffAccount\") objects...");
        CanteenAccount employee = new CanteenAccount("A01PL", "Patrick", 2);  
        CanteenAccount employee2 = new StaffAccount("blah", "blah", 0.25);

        System.out.println (">>Checking initial balances...");
        System.out.println ("  employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
        System.out.println ("  employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());

        System.out.println (">>Buying a $5.00 meal...");
        System.out.println ("  employee...");
        buyAMeal (employee, 5.00);
        System.out.println ("  employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
        System.out.println ("  employee2...");
        buyAMeal (employee2, 5.00);
        System.out.println ("  employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());

        System.out.println (">>Add $5.00 and buy another $5.00 meal...");
        System.out.println ("  employee...");
        employee.topUp(5.0);
        buyAMeal (employee, 5.00);
        System.out.println ("  employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
        System.out.println ("  employee2...");
        employee2.topUp(5.0);
        buyAMeal (employee2, 5.00);
        System.out.println ("  employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());
    }

}

Sample output:

>>Creating employee ("CanteenAccount" and employee2 ("StaffAccount") objects...
>>Checking initial balances...
  employee balance=2.0, creditLimit=5.0
  employee2 balance=0.0, creditLimit=5.0
>>Buying a $5.00 meal...
  employee...
ERROR: 

-----------------------------
You must top-up your balance
Your new balance is: -3.0 GBP
You are: Using Credit
-----------------------------

  employee balance=-3.0, creditLimit=5.0
  employee2...
ERROR: 

------------------------------
Cost exceeds the credit limit.
------------------------------

  employee2 balance=0.0, creditLimit=5.0
>>Add $5.00 and buy another $5.00 meal...
  employee...
ERROR: 

-----------------------------
You must top-up your balance
Your new balance is: -3.0 GBP
You are: Using Credit
-----------------------------

  employee balance=-3.0, creditLimit=5.0
  employee2...
ERROR: 

------------------------------
Cost exceeds the credit limit.
------------------------------

  employee2 balance=5.0, creditLimit=5.0
paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • So in the overridden method payForMeal, In the assignment I need to have a discount which applies to the amount(amount of meal) then the discounted amount is removed from the balance - however the constructor we are given for staffAccount does not have a constructor - it reads in the assignments as: A method to record the cost of a meal. The balance on a StaffAccount object should be amended to reflect discount on the cost of a meal (if the cost does not exceed available balance). – Liam Sanchez-Rodriguez Oct 25 '19 at 23:00
  • so when I create a staff object CanteenAcc employee2 = new StaffAccount("blah", "blah", 0.25), and try to use the payForMeal option, there is to balance for me to pay from – Liam Sanchez-Rodriguez Oct 25 '19 at 23:04
  • I sincerely hope you didn't mark me down. And I honestly don't know what you're going on about with "constructors" :(. Let me type in your code and update my response. – paulsm4 Oct 25 '19 at 23:52