gpt4 book ai didi

java - 无法访问数组的最后一个元素

转载 作者:行者123 更新时间:2023-12-01 18:44:19 25 4
gpt4 key购买 nike

我正在逐行解析 .CSV 文件,我想获取列的值。以我的 .CSV 文件为例:

time;columnA;columnB,ColumnC
27-08-2013 14:43:00; this is a text; this too; same here

所以我所做的是将内容存储在二维字符串数组中(感谢 split())。我的数组制作如下:

array[0][x] = "time".
array[y][x] = "27-08-2013 14:43:00";

它们是 x 个不同的列,但每个列的名称仅存储在第 [0][x] 行上。它们是 y 条不同的行,其中的值存储为字符串。

我的问题如下,我想获取数据的 [x] 位置,但是当我尝试访问数组的最后一个 [x] 元素时。我收到此错误消息

java.lang.ArrayIndexOutOfBoundsException: 17
at IOControl.ReadCsvFile.getPosVar(ReadCsvFile.java:22)
at IOControl.ReadCsvFile.<init>(ReadCsvFile.java:121)
at en.window.Main.main(Main.java:48)

显然我读得太远了,但是怎么样?

这是我的代码:

//Retrieves the x position of the variable var given as parameter.
private int getPosVar(String[][] index, String var)
{
int x = 0;
boolean cond = false;
while((index[0][x] != null) && (cond != true))
{
if (index[0][x].contains(var) == true)
{
cond = true;
}
x++;
}
System.out.println("x = " +x+ " val = " +index[0][x]);
return(x);
}

我想这可能是因为我没有检查我的 x 值是否小于完整字符串。像这样:

x < index[x].length

但事实上我没有改变任何东西,当我给出一个未知的String var时,它也太过分了。为什么?

最佳答案

在使用索引之前检查索引的有效性也是一个好主意:

if ( index == null || index.length == 0 ) return -1;

你的 while 循环应该看起来更像这样:

while ( x < index[0].length )
{
if ( index[0][x] == null )
{
x++;
continue; // skip possible null entries.
}

if ( index[0][x].contains(var) )
{
System.out.println("x = " + x + ", val = " + index[0][x]);
return x; // return the position found.
}
x++;
}
return -1;

使用 for 循环(我更喜欢):

for ( int x = 0; x < index[0].length; x++ )
{
if ( index[0][x] == null )
continue; // skip possible null entries.

if ( index[0][x].contains(var) )
{
System.out.println("x = " + x + ", val = " + index[0][x]);
return x; // return the position found.
}
}

关于java - 无法访问数组的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18489488/

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