英文:
Why do I get an ArrayIndexOutOfBoundsException with this?
问题
Hey there pretty new to Java I have a CSV file that I am scanning line by line (I am assuming) and printing out the details formatted. I keep getting a java.lang.ArrayIndexOutOfBoundsException: 1 what could I be doing wrong?
Here is the CSV file contents.
1,Mazda CX-9,7,Automatic,Premium,150
2,VW Golf,5,Automatic,Standard,59
3,Toyota Corolla,5,Automatic,Premium,55
4,VW Tiguan,7,Automatic,Premium,110
5,Ford Falcon,5,Manual,Standard,60
<!-- -->
String fileName = "CarList.CSV";
File file = new File(fileName);
Scanner input = new Scanner(file);
while (input.hasNextLine())
{
carsAvailableCount++;
String line = input.nextLine();
int length = line.length();
String fields[] = line.split(",");
String carNo = fields[0];
String carName = fields[1];
String seats = fields[2];
String transmission = fields[3];
String carType = fields[4];
String rate = fields[5];
System.out.format("%-9s%-9s%-9s%-9s%-9s%-9s\n", carNo, carName, seats, transmission, carType, rate);
}
英文:
Hey there pretty new to Java I have a CSV file that I am scanning line by line (I am assuming) and printing out the details formatted. I keep getting a java.lang.ArrayIndexOutOfBoundsException: 1 what could I be doing wrong?
Here is the CSV file contents.
1,Mazda CX-9,7,Automatic,Premium,150
2,VW Golf,5,Automatic,Standard,59
3,Toyota Corolla,5,Automatic,Premium,55
4,VW Tiguan,7,Automatic,Premium,110
5,Ford Falcon,5,Manual,Standard,60
<!-- -->
String fileName = "CarList.CSV";
File file = new File(fileName);
Scanner input = new Scanner(file);
while (input.hasNextLine())
{
carsAvailableCount++;
String line = input.nextLine();
int lenght = line.length();
String fields[] = line.split(",");
String carNo = fields[0];
String carName = fields[1];
String seats = fields[2];
String transmission = fields[3];
String carType = fields[4];
String rate = fields[5];
System.out.format("%-9s%-9s%-9s%-9s%-9s%-9s\n", carNo, carName, seats, transmission, carType, rate);
}
答案1
得分: -2
已找到问题,哈哈,我的CSV文件在最后一个条目下面有空行。大家加油。
英文:
Figured out the problem haha, my CSV file had empty lines below my last entry. Cheers everyone.
专注分享java语言的经验与见解,让所有开发者获益!
评论