【发布时间】:2015-01-07 10:31:07
【问题描述】:
我在完成家庭作业时遇到了麻烦,我创建了一个调用另一个类的方法的类。我们得到以下类:
/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
public class BankAccount
{
private double balance;
/**
Constructs a bank account with a zero balance.
*/
public BankAccount()
{
balance = 0;
}
/**
Constructs a bank account with a given balance.
@param initialBalance the initial balance
*/
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
/**
Deposits money into this account.
@param amount the amount to deposit
*/
public void deposit(double amount)
{
balance = balance + amount;
}
/**
Makes a withdrawal from this account, or charges a penalty if
sufficient funds are not available.
@param amount the amount of the withdrawal
*/
public void withdraw(double amount)
{
final double PENALTY = 10;
if (amount > balance)
{
balance = balance - PENALTY;
}
else
{
balance = balance - amount;
}
}
/**
Adds interest to this account.
@param rate the interest rate in percent
*/
public void addInterest(double rate)
{
double amount = balance * rate / 100;
balance = balance + amount;
}
/**
Gets the current balance of this account.
@return the current balance
*/
public double getBalance()
{
return balance;
}
}
然后我收到以下提示:
“实现一个Portfolio类。这个类有两个对象,checking和savings,类型为BankAccount。实现四个方法:
- 公共无效存款(双倍金额,字符串账户)
- public void 取款(双倍金额,字符串账户)
- public void transfer(double amount, String account)
- public double getBalance(String account)
这里的帐户字符串是“S”或“C”。对于存款或取款,它表明哪个账户受到影响。对于转帐,它表示从哪个帐户取钱;这笔钱会自动转入另一个帐户。”
这就是我所做的:
public class Portfolio
{
BankAccount checking;
BankAccount savings;
public void deposit(double x, String y)
{
if (y.equals("C"))
{
checking.deposit(x);
}
else if (y.equals("S"))
{
savings.deposit(x);
}
}
public void withdraw(double x, String y)
{
if (y.equals("C"))
{
checking.withdraw(x);
}
else if (y.equals("S"))
{
savings.withdraw(x);
}
}
//public void transfer(double amount, String account)
//{
// add later
//}
public double getBalance(String account)
{
if (account.equals("C"))
{
return checking.getBalance();
}
else
{
return savings.getBalance();
}
}
}
但是我什至无法使用存款方式。当我运行这个程序时...
public class PortfolioTester
{
public static void main(String [] args)
{
Portfolio money = new Portfolio();
money.deposit(700, "S");
}
}
我收到此错误:
线程“main”中的异常 java.lang.NullPointerException 在 Portfolio.deposit(Portfolio.java:14) 在 PortfolioTester.main(PortfolioTester.java:6)
我想我从根本上误解了课程的运作方式。有人能指出我正确的方向吗?
【问题讨论】:
-
BankAccount checking;声明了一个BankAccount类型的字段,但它没有初始化它,所以它仍然为空。您需要在某处将new BankAccount()分配给它。也许在Portfolio的构造函数中。 -
ooohhh,我想我现在明白了,谢谢。如果我现在无法弄清楚,我可能会提出另一个问题,但谢谢!
-
更新:哈!谢谢!
标签: java class compiler-errors