0

I'm trying to grasp some comments that were made to me by my professor on a programming assignment. The assignment was to write a program that calls upon another class. This program was to take 2 investors with different starting balances and show how much interest they would collect after a 15 month period. Just so everyone is clear, my assignment has already been graded, so any critiques or changes would NOT be helping me complete my homework, but ONLY to help me understand what I did wrong and how I can fix it for future assignments. I received a 90% on my program for my grade.

The following comments were made about my assignment:

"Your setInterest method was to be a class method not an instance method. Also, your call should have been

IWUnit4Ch13Investor.setInterest(rate);"

I'm not exactly following what I did wrong or how I can fix it. Can someone please show me what I did wrong and possibly explain why it's wrong so that I may correct my habits for future assignments and grasp how to correctly write code?

// IWUnit4Ch13.java
import java.util.*;
import java.util.Scanner;

// main class
public class IWUnit4Ch13 {

    public static void main(String[] args) {

        // Declares local variables
        double rate, INTEREST_RATE;

        // Instantiate investor1 & investor2 objects using a two parameter constructor
        IWUnit4Ch13Investor investor1 = new IWUnit4Ch13Investor(1001, 2000);
        IWUnit4Ch13Investor investor2 = new IWUnit4Ch13Investor(2001, 4000);
        Scanner input = new Scanner(System.in);

        // Receives the APR by the user
        System.out.print("Please enter the APR in the form of .05 for 5%: ");
        rate = input.nextDouble();

        // Moves the decimal 2 places to the left (used later)
        INTEREST_RATE = rate * 100;

        // Sets the interest rate using a class variable
        investor1.setInterestRate(rate);
        investor2.setInterestRate(rate);

        // Prints the header for the table
        System.out.printf("Monthly balances for one year with %.2f annual interest:\n\n", rate);
        System.out.println("Month Account #   Balance Account #   Balance");
        System.out.println("----- ---------   ------- ---------   -------");

        // Loop that prints each month on the table
        // Uses class variables to add interest and get balance for display
        for (int i = 1; i <= 15; i++) {
            investor1.addInterest();
            investor2.addInterest();
            System.out.printf("%5d %9d %9.2f %9d %9.2f\n", i, investor1.getACCOUNT_NUMBER(), investor1.getBalance(), investor2.getACCOUNT_NUMBER(), investor2.getBalance());
            }

        // Prints the calculated interest earned by both investors
        System.out.printf("\nInvestor1 earned : %.2f", investor1.getInterest());
        System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
        System.out.print("%\n");
        System.out.printf("Investor2 earned : %.2f", investor2.getInterest());
        System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
        System.out.print("%\n\n");

    } // end of internal main
} // end of main class

// Creates IWUnit4Ch13Investor.java which is used in IWUnit4Ch13.java
public class IWUnit4Ch13Investor extends IWUnit4Ch13 {

    // All variables are declared private
    private static double interestRate; // class variable
    private final int ACCOUNT_NUMBER;   // declare constant ACCOUNT_NUMBER
    private double balance;             // instance variable called balance
    private double initialBalance;      // to hold the initial balance
    private double interest;            // to count how much interest was made
    private double INTEREST_RATE;       // used to convert the float interestRate to int

    // Two parameter constructor to initialize account number and balance
    public IWUnit4Ch13Investor(int acctNum, double initialBalance) {
        this.initialBalance = initialBalance;
        this.ACCOUNT_NUMBER = acctNum;
        balance = initialBalance;
    }

    // To return the balance to parent
    public double getBalance() {
        return balance;
    }

    // Class method to set the annual interest rate
    public void setInterestRate(double rate) {
        interestRate = rate;
    }

    // Method to add interest based on balance * interestRate / 12
    public void addInterest() {
        balance += balance * interestRate/12.0;
    }

    // To get account number in parent
    public int getACCOUNT_NUMBER() {
        return ACCOUNT_NUMBER;
    }

    // Used to get the amount of interested earned during 15 months
    public double getInterest() {
        interest = balance - initialBalance;
        return interest;
    }
} // end of class

Thank you all in advance for your help.

Community
  • 1
  • 1

2 Answers2

0

Terms

First of, please don't confuse terms. A variable is different to a method:

// A class
public class Dog {
    // Member variable
    private String name;

    // Method
    public void bark() {
        // Variable
        String textToBark = "Wuff";
        // Call to a method
        System.out.println(textToBark);
    }
}

Elsewhere:

// Creating a new instance of class "Dog"
// and saving a reference to it inside a variable
Dog bello = new Dog("Bello");

Explanation

Your teacher said he wants the setInterest to be a class method instead of an instance method. What he wants to say with that is that it should be declared static and thus not belonging to instances of the class but to the class itself. Here is more on what static means for methods: Java: when to use static methods


Solution

So the method should look like this:

// Method to set the annual interest rate
public static void setInterestRate(double rate) {
    IWUnit4Ch13Investor.interestRate = rate;
}

Where interestRate then also needs to be declared static (which you already did):

// To count how much interest was made
private static double interestRate;

To indicate the access of static variables one should add the class name before, so instead write it like this:

// Method to add interest based on balance * interestRate / 12
public void addInterest() {
    balance += balance * IWUnit4Ch13Investor.interestRate / 12.0;
}

The same holds for calling static methods, instead of

investor1.setInterestRate(rate);
investor2.setInterestRate(rate);

do this

IWUnit4Ch13Investor.setInterestRate(rate);

Due to the nature of static you then also need to set this only once since static variables are shared by all instances of that class.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • 1
    Thank you very much Zabuza. This helps break it down for me in a way that I understood. I struggled with figuring out how to call the class AFTER I had declared the objects. I thought I was supposed to declare the objects first in the code. It makes more sense to simply get all the information needed that applies to both investors first, then create the objects to do the separate calculations. So I guess by setting the interest rate by saying IWUnit4Ch13Investor.setInterestRate(double rate), any object I create from IWUnit4Ch13Investor will have the same rate. Thank you! This makes sense – William Irizarry Nov 15 '17 at 08:14
0

So a static variable is shared by all instances of the class.

If you want all investors to be forced to share the same interest rate, use a static variable.

Methods that only affect static variables should (https://www.ietf.org/rfc/rfc2119.txt) be declared static:

public static void setInterestRate(double rate) {
    interestRate = rate;
}

private static double interestRate;

You would then call the static method by specifying the class name, not the instance variable. Note that you can call the static method before you even have any instances of the class, and you only need to call it once:

Investor.setInterestRate(0.05);

Investor i1 = new Investor();
Investor i2 = new Investor();

double r1 = i1.calculateBalance();
double r2 = i2.calculateBalance();

If you want each investor to be able to have different interest rates, do not use a static variable, use a member variable and method:

public void setInterestRate(double rate) {
    interestRate = rate;
}

private double interestRate;

You then call the method by specifying the instance variable:

Investor i1 = new Investor();
Investor i2 = new Investor();

i1.setInterestRate(0.04);
i2.setInterestRate(0.06);

double r1 = i1.calculateBalance();
double r2 = i2.calculateBalance();

Also, none of that really matters because the output is wrong:

double monthly_rate = pow(10.0, log10(1.0 + yearly_rate) / 12.0) - 1.0;

The system shall not fail

Abdul Ahad
  • 826
  • 8
  • 16