如何将变量设置为类方法而不是静态方法

时间:2017-11-14 10:09:36

标签: java class methods instance

我试图抓住我的教授在编程任务中向我提出的一些评论。作业是编写一个调用另一个类的程序。该计划旨在让2位投资者拥有不同的期初余额,并显示他们在15个月后会收取多少利息。  所以每个人都很清楚,我的作业已经被评分,所以任何批评或改变都不会帮助我完成我的作业,但只是为了帮助我理解我做错了什么以及如何为将来的作业修复它。我的成绩获得了90%的成绩。

以下评论是关于我的任务:

  

"你的setInterest方法是一个类方法而不是一个实例   方法。此外,您的电话应该是

IWUnit4Ch13Investor.setInterest(rate);"

我并没有完全遵循我的错误或如何解决它。有人可以告诉我我做错了什么,并可能解释为什么它错了,以便我可以纠正我未来任务的习惯并掌握如何正确编写代码?

// 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

提前感谢大家的帮助。

2 个答案:

答案 0 :(得分:0)

条款

首先,请不要混淆条款。变量与方法

不同
// 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);
    }
}

其他地方:

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

说明

您的老师说他希望setInterest成为类方法而不是实例方法。他想说的是它应该被声明为static,因此不是属于类的实例,而是属于类本身。以下是static对方法的含义:Java: when to use static methods

解决方案

所以方法应如下所示:

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

其中interestRate还需要声明static(你已经做过):

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

要指示static变量的访问权限,应该先添加类名,所以请改写如下:

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

同样适用于调用static方法,而不是

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

这样做

IWUnit4Ch13Investor.setInterestRate(rate);

由于static的性质,您还需要设置一次,因为static变量共享 所有实例类。

答案 1 :(得分:0)

所有类的实例静态变量共享

如果您希望所有投资者被迫分享相同的利率,请使用静态变量。

影响静态变量的方法应该(https://www.ietf.org/rfc/rfc2119.txt)声明为static:

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

private static double interestRate;

然后,您可以通过指定类名而不是实例变量来调用静态方法。请注意,您甚至可以在拥有该类的任何实例之前调用静态方法,并且只需要调用一次:

Investor.setInterestRate(0.05);

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

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

如果您希望每个投资者能够拥有不同的利率,使用静态变量,请使用成员变量和方法:

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

private double interestRate;

然后通过指定实例变量来调用该方法:

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

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

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

此外,由于输出错误,这一切都不重要:

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

系统不会失败