设置具有特定参数的类

时间:2014-12-17 11:52:05

标签: java class parameters

任何人都可以向我解释为什么这不起作用以及如何设置此类以使用指定参数运行? (初始余额)我想从我的主程序运行这个类,并将一个特定参数作为初始余额传递。我是否需要将起始平衡设置为类变量?

public class LoanAccount
{
static float interestRate = 0.006F;
private float balance;

public LoanAccount(float StartBalance)
{
    balance = StartBalance;
}

public float getBalance(){
    return balance;
}

public void addInterest(){
    float interest = balance * interestRate;
    balance = balance + interest;
}

public void makePayment(float LPaid){
    balance = balance - LPaid;
}

public static void main(){
    LoanAccount BankLoan = new LoanAccount(StartBalance); 

}

}

4 个答案:

答案 0 :(得分:0)

在这一行:

LoanAccount BankLoan = new LoanAccount(StartBalance); 

StartBalance未定义。您需要为构造函数提供实际值,或者使用值初始化的浮点变量。

答案 1 :(得分:0)

下面

LoanAccount BankLoan = new LoanAccount(StartBalance);

你只需要

LoanAccount BankLoan = new LoanAccount(1500.0f);

或您想要开始的任何余额。

答案 2 :(得分:0)

您可以将StartBalance作为命令行参数传递:

public static void main(String[] args)
{
    float StartBalance = 0.0;
    try {
        if (args.length > 0) {
            StartBalance = Float.parseFloat(args[0]);
            LoanAccount BankLoan = new LoanAccount(StartBalance);
        }
    }
    catch (NumberFormatException exc) {
        System.out.println("invalid input : " + args[0]);
    } 
}

答案 3 :(得分:0)

你没有初始化StartBalance,你打算在创建LoanAccount时传递给构造函数。你可以用两种方式做到:

 LoanAccount BankLoan = new LoanAccount(10.0f);

或者你可以在main方法中定义一个局部变量,如:

float initialBalance = 10.0f;
LoanAccount BankLoan = new LoanAccount(initialBalance);
LoanAccount BankLoan2 = new LoanAccount(initialBalance);