为什么在这里我会得到一个 ArrayIndexOutOfBoundsException 错误?

huangapple 未分类评论42阅读模式
英文:

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 = &quot;CarList.CSV&quot;;
    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(&quot;,&quot;);
        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(&quot;%-9s%-9s%-9s%-9s%-9s%-9s\n&quot;, 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.

huangapple
  • 本文由 发表于 2020年4月10日 16:56:16
  • 转载请务必保留本文链接:https://java.coder-hub.com/61136993.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定