gpt4 book ai didi

java - 从 CSV 文件中获取随机元素

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

我在从 CSV 文件中获取随机元素时遇到问题。这是我的代码

public  String[] generateNames(String Name) 

BufferedReader br = new BufferedReader(newFileReader("c:\\users\\listofcities.csv"));


Random generator = new Random();

int row = generator.nextInt(1);

String[] arrayValues = new String[row];

for (int i=1; i<arrayValues.length; i++) {
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, "\n");
while (st.hasMoreTokens()) {
//get next token and store it in the array
arrayValues[row] = st.nextToken();

}

}
row++;
}
//close the file
br.close();

return arrayValues;
}

每当我的行值不是 1 时,我都会收到 arrayoutofbounds 异常。任何人都可以让我走上正轨,因为我的代码很糟糕。

最佳答案

您正在使用 Random 类的 public int nextInt(int bound),它返回 0(含)和指定的 bound 之间的值值(独占)。

String[] arrayValues = new String[row]; 此行生成大小为 0 或 1 的数组。因此,当您尝试访问 arrayValues[i] 时,其中 i 大于它抛出异常的数组大小。

关于java - 从 CSV 文件中获取随机元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35967527/

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