简体   繁体   English

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

[英]How to set a variable as a class method and not as a static method

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. 该计划将以2个初始余额不同的投资者为对象,并显示他们在15个月后会收取多少利息。 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. 我的课程成绩达到了90%。

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 “您的setInterest方法应该是一个类方法,而不是实例方法。而且,您的调用应该已经

 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. 预先感谢大家的帮助。

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 . 您的老师说他希望setInterest是一个类方法而不是实例方法 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. 他要说的是应该将其声明为static ,因此不属于类的实例,而是属于类本身。 Here is more on what static means for methods: Java: when to use static methods 这里有更多关于static方法的含义: Java:何时使用静态方法


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): 然后还需要将interestRate声明为static (您已经这样做了):

// 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: 为了表明对static变量的访问,应该在类名之前添加类名,因此应这样写:

// 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 调用static方法也是如此,而不是

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. 由于static的性质,您还只需要设置一次,因为该类的所有实例共享 static变量。

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: 影响静态变量的方法应( https://www.ietf.org/rfc/rfc2119.txt )声明为静态:

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 系统不得失败

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM