gpt4 book ai didi

java - Java 类的问题

转载 作者:行者123 更新时间:2023-11-30 03:40:54 26 4
gpt4 key购买 nike

我在完成家庭作业时遇到问题,无法创建一个从另一个类调用方法的类。我们有以下类(class):

/**
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 类。该类有两个对象,即 BankAccount 类型的支票和储蓄。实现四个方法:

  • 公共(public)无效存款(双倍金额,字符串账户)
  • public void提款(双倍金额,字符串帐户)
  • 公开无效转账(双倍金额,字符串账户)
  • 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");

}

}

我收到此错误:

Exception in thread "main" java.lang.NullPointerException at Portfolio.deposit(Portfolio.java:14) at PortfolioTester.main(PortfolioTester.java:6)

我想我从根本上误解了类(class)的运作方式。有人能指出我正确的方向吗?

最佳答案

您收到这些错误是因为您必须初始化在 deposit 方法中使用的 BankAccount 类。我建议在 Portfolio 类中放置一个构造函数(类通常应该具有初始化类属性的构造函数)。在 Portfolio 构造函数中,您可以初始化 BankAccount 类“checking”和“ savings”。

请记住,对于非静态方法,您必须拥有类的实例才能调用其方法。

关于java - Java 类的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26855345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com