需要帮助理解特定的未解决编译错误。

9 浏览
0 Comments

需要帮助理解特定的未解决编译错误。

我需要创建一个带有账户类的测试账户程序。以下是我想出来的代码:\n

package accounts;
import java.util.Date;
public class TestAccount {
    public static void main(String[] args) {
        java.util.Date date = new java.util.Date();
        Account firstaccount = new Account (1111, 10000.00, 0.045);
        System.out.println("Transaction started: " + date.toString());
        System.out.println("User's ID is: " + firstaccount.getId());
        System.out.println("User's balance is: " + firstaccount.getBalance());
        System.out.println("The montlhly interest rate is: " + firstaccount.getMonthlyInterestRate());
        System.out.println("Balance after withdraw is: " + firstaccount.withdraw(1000));
        System.out.println("Balance after deposit is: " + firstaccount.deposit(3000));
        System.out.println("Transaction complete.");
    }
    
    class Account {
        private int id = 0;
        private double balance = 0.0;
        private double annualInterestRate = 0.0; 
        
        public Account (int newId, double newBalance, double newAnnualInterestRate) {
            id = newId;
            balance = newBalance;
            annualInterestRate = newAnnualInterestRate;
        }
        
        public int getId() {
            return id;
        }
        
        public double getBalance () {
            return balance;
        }
        
        public double getAnnualInterestRate () {
            return annualInterestRate;
        }
        
        public double getMonthlyInterestRate () {
            return annualInterestRate/12;
        }
        
        public double withdraw (double value) {
            return balance -= value;
        }
        
        public double deposit (double value) {
            return balance += value;
        }
        
        public void setId (int newId) {
            id = newId;
        }
        
        public void setBalance (double newBalance) {
            balance = newBalance;
        }
        
        public void setAnnualInterestRate (double newAnnualInterestRate) {
            annualInterestRate = newAnnualInterestRate;
        }
    } 
}

\n这是我遇到的错误:\n\"Exception in thread \"main\" java.lang.Error: Unresolved compilation problem: \nNo enclosing instance of type TestAccount is accessible. Must qualify the allocation with an enclosing instance of type TestAccount (e.g. x.new A() where x is an instance of TestAccount).\nat accounts.TestAccount.main(TestAccount.java:12)\" \n请帮助我理解我需要做什么。谢谢。

0
0 Comments

需要帮助理解特定的未解决编译错误

您有一个嵌套类。在Java中,当非静态类嵌套在非静态类中时,new语句需要像错误消息所说的那样:

TestAccount ta = new TestAccount();
TestAccount.Account ta_a = ta.new Account();

语法很丑陋,但嵌套类也是如此。

有关更多信息,请参见文档

希望对你有所帮助。

通过使用Account firstaccount = new TestAccount().new Account()解决了问题。

0