Reputation: 241
The program asks user to input some amounts and that amount(s) will be stored into an array. But in my case, while inputting amount, the program shows the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at bankapplication.DepositWithdraw.deposit(DepositWithdraw.java:17)
at bankapplication.BankApplication.main(BankApplication.java:46)
My code
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");
}
}
[NOTE: this class and it's method are meant to be called in my main class. I haven't shown my main class here, but I will edit the post if needs]
Upvotes: 2
Views: 73
Reputation:
You defind the defAmArr before transSum got any vaule. That caused the array to be with a different value (or without value). to solve it just do the new int[transSum]; after you are getting he value to transSum
Upvotes: 1
Reputation: 311188
TransacNum
, by default is 0
, until you assign it a value. The problem is that you use it to initialize depAmArr
before that. Just initialize it after TransacNum
, and you should be fine:
TransacNum = input.nextInt();
depAmArr[] = new int[TransacNum];
Upvotes: 2
Reputation: 12196
Because you never initilize it with the size you got from the user input.
The class initilization has put default on all class members, TransacNum
included. (value: 0)
Those the size of the array was set to array with the size of 0.
You should only create the array when the size is known. i.e After the user enters the size.
Example:
TransacNum = input.nextInt();
depAmArr[] = new int[TransacNum]
Also, You should change int depAmArr[] = new int[TransacNum];
into int depAmArr[];
Upvotes: 1