我正在开发一个程序,该程序从包含银行帐户列表的文件中读取。我一直遇到IndexOutOfBoundsException错误,我不知道为什么。当我把银行账户直接放在代码中(而不是从文件中读取)时,它工作得很好,这使我相信我的while循环在某处搞砸了。我怀疑它没有正确循环但我并不积极。不幸的是,我没有很多关于while循环的经验。任何帮助将不胜感激,谢谢:)
我正在阅读的文件,按照帐户类型/名称/价值/费率的顺序列出:
1,Waterford Ellingsworth,4350.0,0.002
2,Bethanie Treadwell,500.0,0.35
3,Ira Standish,50000,0.1,59,0.1
实际程序本身:
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
编辑包含输出:
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)
这是我整个计划的链接:https://drive.google.com/drive/folders/0BysdkYqrEP7kazNhMXpQSzd4bUE?usp=sharing
答案 0 :(得分:1)
替换
swiper.slideTo(activeSlide);
带
Scanner infile = new Scanner("C:/Users/Josh/Desktop/prog5input.csv");
作为您的代码,扫描仪的输入流将是字符串" c:...."而不是它代表的文件。
答案 1 :(得分:0)
我下载了你的谷歌驱动程序,它对我来说很有魅力,有以下变化..
Scanner infile = new Scanner(new FileInputStream("C://Users//Josh//Desktop//prog5input.csv"));
确保您在此处指定了正确的文件路径..
计划5,Josh Correia,cssc0491 创建帐户...... Waterford Ellingsworth4350.00.002Customer:Waterford Ellingsworth,储蓄账户1余额:$ 4350.00 客户:Bethanie Treadwell,支票账户2余额:$ 500.00 客户:Ira Standish,IRA储蓄账户3余额:$ 50000.00,支付年龄= 59,提前取款罚款= 0.1
执行交易...... 储蓄账户1余额:4550.00美元 支票账户2余额:$ 286.87 IRA储蓄账户3余额:$ 50000.00,支付年龄= 59,提前取款罚款= 0.1
更新帐户... 储蓄账户1余额:4559.10美元 支票账户2余额:$ 286.52 IRA储蓄账户3余额:55000.00美元,支付年龄= 59,提前提款罚款= 0.1