我在完成家庭作业时遇到了麻烦,创建了一个从另一个类调用方法的类。我们得到以下课程:
/**
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;
}
}
然后我给出了以下提示:
"实施班级投资组合。这个类有两个对象,BankAccount类型的检查和保存。实现四种方法:
此处的帐户字符串为" 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)
我想我有点误解了关于课程如何运作的问题。有人能指出我正确的方向吗?
答案 0 :(得分:1)
您收到这些错误是因为您必须初始化BankAccount
方法中使用的deposit
类。我建议在Portfolio
类中放置一个构造函数(类通常应该有构造函数来初始化类属性)。在Portfolio
构造函数中,您可以初始化BankAccount
类“checking
”和“savings
”。
请记住,对于非静态方法,您必须有一个类的实例来调用其方法。
答案 1 :(得分:1)
问题是您已在BankAccount
课程中创建Portfolio
,但尚未对其进行初始化。它就像这样做:
int myInt;
System.out.println(myInt);
会发生什么?你无法编译它,因为它还没有被初始化。但是当你的变量在类中时,在其他类中,编译器不能轻易地告诉它是否已经初始化。您必须为Portfolio
类创建构造函数并初始化BankAccount
对象,如下所示:
public class Portfolio
{
BankAccount savings;
BankAccount checking;
public Portfolio()
{
savings = new x(); //Replace x with what you think needs to be there
checking = new x(); //Replace x with what you think needs to be there
}
}