如何消除索引错误超出范围异常[重复]

问题描述 投票:0回答:2

您好,我继续在if(numList.get(x)==“” && numList.get(x + 1)==“”)行中获取java.lang.IndexOutOfBoundsException。我该如何解决?

BufferedReader br = null;
        String row;
        String[] data = null;
        List<String> numList = new ArrayList<String>();

        BufferedReader csvReader = new BufferedReader(new FileReader("input file lab5.csv"));
        while ((row = csvReader.readLine()) != null) {
            data = row.split(",");
            // do something with the data

            for(int x=0; x<data.length; x++) {
                numList.add(data[x]);
            }
            numList.add(" ");
        }

        System.out.println("Make sure excel file is on src.\nNumbers extracted from file: "+numList);
        int n=0;

        for(int x=0; x<numList.size(); x++) {
            if(numList.get(x) == " " && numList.get(x+1) == " ") {
                n = x+1;
                break;
java csv indexoutofboundsexception
2个回答
0
投票

为最后的索引处理添加一个签入if子句(x

if (numList.get(x) == " " && x < numList.size()-1 && numList.get(x+1) == " ") {


0
投票

在最后一个for循环中,最大的迭代器值为numList.size(),但是您引用的是x+1,因此可能要多一个。您必须降低限制:

for(int x = 0; x < numList.size() - 1; x++) {
    if(numList.get(x).equals(" ") && numList.get(x + 1).equals(" ")) {
        n = x + 1;
        break;
© www.soinside.com 2019 - 2024. All rights reserved.