Java Completive错误银行帐户类

时间:2014-12-24 03:52:04

标签: java compiler-errors

更新:通过添加到实例字段来修复错误。 - 谢谢。

第二个问题:我可以将“activeaccount”变成一个流量变量并且可能是实际账户吗?如果是这样,怎么样?

当我编译程序时,我遇到了在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();
    }
  }

3 个答案:

答案 0 :(得分:2)

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);

答案 1 :(得分:0)

这是因为您在构造函数中创建了一个本地变量activeaccount,当构造函数完成时,该变量超出了范围。

将声明移动到类级别,并在构造函数中简单地实例化它,如:

public class Account {
    private BankAccount activeaccount;
    public Account() {
        activeaccount = new BankAccount("Seth Killian", "Savings", 500.00, 6.0, 0.25, 10000.00);
    }
    :
    and so on.

答案 2 :(得分:0)

BankAccount activeaccount = new BankAccount("Seth Killian", 
   "Savings", 500.00, 6.0, 0.25, 10000.00);

您在构造函数中声明了一个局部变量。它仅在构造函数的范围内可用。如果您希望它是实例变量,则应将其添加到类定义中。

private BankAccount activeaccount;   

public Account() {
    activeaccount = new BankAccount("Seth Killian", 
       "Savings", 500.00, 6.0, 0.25, 10000.00);
}