该程序要求用户输入一些金额,该金额将存储到数组中。
但是对于我来说,在输入金额时,程序显示错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at bankapplication.DepositWithdraw.deposit(DepositWithdraw.java:17)
    at bankapplication.BankApplication.main(BankApplication.java:46)


我的密码

package bankapplication;

import java.util.*;

public class DepositWithdraw {

    Scanner input = new Scanner(System.in);
    int TransacNum;
    double withAm;
    int depAmArr[] = new int[TransacNum];

    public void deposit() {
        System.out.println("Depositing:\nHow many transaction you want to make? ");
        TransacNum = input.nextInt();
        for (int i = 0; i < TransacNum; i++) {
            System.out.println("Enter amount " + (i + 1) + ":");
            depAmArr[i] = input.nextInt();
        }
        System.out.println("You are done! Choose other option if you want to continue.\n");
    }

}


[注意:该类及其方法应在我的主类中调用。我没有在这里显示我的主班,但是如果需要,我将编辑该帖子]

最佳答案

TransacNum,默认情况下为0,直到您为其分配值为止。问题在于您可以在此之前使用它来初始化depAmArr。只需在TransacNum之后初始化它,就可以了:

TransacNum = input.nextInt();
depAmArr[] = new int[TransacNum];

09-30 23:41