I am working on a program that reads from a file with a list of bank accounts. I keep encountering an IndexOutOfBoundsException error and I'm not sure why. When I put the bank accounts straight in the code (not reading from a file) it works just fine which leads me to believe that my while-loop is messed up somewhere. I suspect that it is not looping correctly but I am not positive. I don't have very much experience with while-loops unfortunately.
File I am reading from, listed in order of accountType/name/worth/rate:
1,Waterford Ellingsworth,4350.0,0.002
2,Bethanie Treadwell,500.0,0.35
3,Ira Standish,50000,0.1,59,0.1
The actual program itself:
Scanner infile = new Scanner("C:/Users/Josh/Desktop/prog5input.csv");
while (infile.hasNextLine()) {
Scanner s2 = new Scanner(infile.nextLine()); // put string from file into second Scanner object
s2.useDelimiter(",");
if (s2.hasNextInt()) {
int type = s2.nextInt();
if (type == 1) {
String accountHolder = s2.next();
double accountInitial = s2.nextDouble();
double accountRate = s2.nextDouble();
bank.addNewAccount(new SavingsAccount(accountHolder, accountInitial, accountRate));
// read fields for Type 1 accounts and create new Type 1 object
}
else if (type == 2) {
String accountHolder = s2.next();
double accountInitial = s2.nextDouble();
double accountCostPerMonth = s2.nextDouble();
bank.addNewAccount(new CheckingAccount(accountHolder, accountInitial, accountCostPerMonth));
}
else if (type == 3) {
String accountHolder = s2.next();
double accountInitial = s2.nextDouble();
double accountRate = s2.nextDouble();
int disbursementAge = s2.nextInt();
double earlyWithdrawalPenalty = s2.nextDouble();
bank.addNewAccount(new IRAAccount(accountHolder, accountInitial, accountRate, disbursementAge, earlyWithdrawalPenalty));
}
} //ends if statement s2.hasNextInt()
// now go to top of loop, check infile to see if there is another line to read
} //ends while loop
Edited to include the output:
Creating accounts...
Performing transactions...
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Bank.getAccountByIndex(Bank.java:28)
at BankDriverFileInput.main(BankDriverFileInput.java:58)
Here's a link to my entire program: https://drive.google.com/drive/folders/0BysdkYqrEP7kazNhMXpQSzd4bUE?usp=sharing
Scanner infile = new Scanner("C:/Users/Josh/Desktop/prog5input.csv");scans the filename, not the file.