从CSV文件中随机获取元素

3

我在从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时,我会得到一个数组越界异常。有人能给我指点一下吗,因为我的代码出了问题。
2个回答

0

你正在使用Random类的public int nextInt(int bound)方法,该方法返回介于0(包括0)和指定bound值(不包括该值)之间的值。

String[] arrayValues = new String[row];这行代码会生成大小为0或1的数组。因此,当你尝试访问arrayValues[i]时,如果i大于数组大小,则会抛出异常。


0
你的代码问题在于你生成的值只有0或1,所以将随机数生成语句改为这样。
 int randomNum = minimum + rand.nextInt((maximum - minimum) + 1);

minimum = 范围内的初始值, maximum = 范围内的最终值


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接