更新:通过添加到实例字段来修复错误。 - 谢谢。
第二个问题:我可以将“ Activity 帐户”设置为可变变量,并为实际帐户提供机会吗?如果是这样,怎么办?
编译程序时,我在MainMenu方法中遇到找不到符号“activeaccount”的问题。我对为什么会收到此错误感到困惑,因为我在构造函数中建立了“activeaccount”对象。有任何想法吗?先感谢您!
public class Account
{
/**
* Constructor for objects of class Account
*/
public Account()
{
BankAccount activeaccount = new BankAccount("Seth Killian", "Savings", 500.00, 6.0, 0.25, 10000.00);
}
public void MainMenu()
{
Scanner in = new Scanner (System.in);
switch (in.nextInt())
{
case 0:
Initialize();
case 1: //Check balance
activeaccount.printBalance();
SelectOption();
case 2: //Make a deposit
double amount;
System.out.print("Deposit Amount: $");
amount = in.nextDouble();
activeaccount.deposit(amount);
SelectOption();
case 3: //Make a withdrawl
System.out.print("Withdrawl Amount: $");
amount = in.nextDouble();
activeaccount.withdrawl(amount);
SelectOption();
case 4: //Apply Annual Interest
activeaccount.addInterest();
SelectOption();
case 5: // Print Log
activeaccount.printLog();
SelectOption();
case 6: // Exits application
System.exit(0);
default: // Unrecognized Selection
System.out.println ("Error: Selection Unrecognized");
SelectOption();
}
}
最佳答案
activeaccount
仅存在于构造函数的scope中。如果要在该类的其他部分访问activeaccount
,请为其创建一个instance variable:
private BankAccount activeaccount; // the instance variable
public Account() {
activeaccount = new BankAccount("Seth Killian", "Savings", 500.00, 6.0, 0.25, 10000.00);
}
或一行(可以省略构造函数):
private BankAccount activeaccount = new BankAccount("Seth Killian", "Savings", 500.00, 6.0, 0.25, 10000.00);