0

Account という名前のクラスを作成しました。次に、型クラスのオブジェクトをインスタンス化しています。すべてのコードはファイル TestAccount に保存されます。しかし、システムは以下に示すようにエラーを出します

スレッド「メイン」での例外 java.lang.ExceptionInInitializerError at testaccount.TestAccount.main(TestAccount.java:8) 原因: java.lang.RuntimeException: Uncompilable source code - クラス Account はパブリックです。Account という名前のファイルで宣言する必要があります.java at testaccount.Account.(TestAccount.java:20) ... 1 つ以上の Java 結果: 1

以下は私のコードです:

package testaccount;

public class TestAccount
{
public static void main(String[] args)
{

Account Account1=new Account();
Account1.setId(1122);
Account1.setBalance(20000);
Account1.setAnnualInterestRate(4.5);
System.out.println("The monthly interest rate is " + Account1.getMonthlyInterestRate());
System.out.println("The balance after the withdrawal is "+ Account1.withdraw(2000));
System.out.println("The balabce after the deposit is " + Account1.deposit(3000));

}

}

public class Account 
   {
      private int id;
      private double balance;
      private double annualInterestRate;
      private static long dateCreated;

      public Account()
      {
          id=0;
          balance=0;
          annualInterestRate=0;
          dateCreated=System.currentTimeMillis();
      }

      public Account(int newId,double newBalance)
      {
          id=newId;
          balance=newBalance;
      }

      public int getId()
      {
          return id;
      }
      public void setId(int newId)
      {
           id=newId;
      }

      public double getbalance()
      {
          return balance;
      }
      public void setBalance(double newBalance)
      {
           balance=newBalance;
      }

      public double getAnnualInterestRate()
      {
          return annualInterestRate;
      }
      public void setAnnualInterestRate(double newAnnualInterestRate)
      {
           annualInterestRate=newAnnualInterestRate;
      }

      public static long getDateCreate()
      {
          return dateCreated;
      }

      public double getMonthlyInterestRate()
      {
          return (annualInterestRate/12);
      }

      public double withdraw(double newWithdraw)
      {
          return (balance-newWithdraw);
      }

      public double deposit(double deposit)
      {
          return (balance+deposit);
      }
}

誰かが私が間違っていることを教えてもらえますか?

4

2 に答える 2

1

という名前の新しいファイルを作成しAccount.java、そこにアカウント クラスを配置する必要があります。これは、別のクラスからアカウントを呼び出すと、jvm が探しに行きAccount.class、アカウント クラスが名前付きのファイルにある場合、TestAccount.classそれを見つけることができないためです。

そうしないと、コンパイラはファイルをコンパイルしません

両方のクラスが同じパッケージ (フォルダー) にある限り、2 つを「リンク」するために特別なことをする必要はありません。

もちろん、クラスを入れ子にしたい場合を除きます。その場合は、Accountクラスをクラスの中に入れますTestAccount。これは非常に厄介なのでお勧めしませんが。

于 2013-11-01T00:28:35.933 に答える
0

これは良い方法ではありません。すでに存在するソリューションの方が優れていますが、Account クラスを TestAccount 内に移動して静的にすることができます (静的をクラス定義の前に置きます)。それもうまくいきます。

于 2013-11-01T00:34:43.783 に答える