gpt4 book ai didi

java - while循环读取csv文件越界

转载 作者:行者123 更新时间:2023-12-02 13:37:21 25 4
gpt4 key购买 nike

我正在开发一个从包含银行帐户列表的文件中读取的程序。我不断遇到 IndexOutOfBoundsException 错误,但不确定原因。当我将银行账户直接放入代码中(而不是从文件中读取)时,它工作得很好,这让我相信我的 while 循环在某个地方搞砸了。我怀疑它没有正确循环,但我并不肯定。不幸的是,我对 while 循环没有太多经验。

我正在读取的文件,按帐户类型/名称/值(value)/费率的顺序列出:

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

最佳答案

替换

Scanner infile = new Scanner("‪C:/Users/Josh/Desktop/prog5input.csv");

Scanner infile = new Scanner(new FileInputStream("‪C:/Users/Josh/Desktop/prog5input.csv"));

因为您的代码,Scanner 的输入流将是字符串“c:....”,而不是它代表的文件 .

关于java - while循环读取csv文件越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42918094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com