有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java ArrayIndexOutofBoundsException处理数组

我试图从excel文件中读取数字并将它们放入数组中,但我得到了一个越界异常。。。excel文件有2列,每列32行。。。第一列(5位数)中的数字将插入名为allInputs的数组中,而第二列(3位数)中的数字将插入名为allTargets的数组中。。。以下是我的代码

String[] allInputs = new String[32];
    String[] allTargets= new String[32];

     //Read the values from csv file 

    //Input file which needs to be parsed
    String fileToParse = "C:\\Users\\ROBMARYAN\\Documents\\UOM\\Bsc IT Comp & Business\\3rd Yr\\Business Intelligence\\NeuralNetAssignment\\src\\inputs.csv";
    BufferedReader fileReader = null;

    //Delimiter used in CSV file
    final String DELIMITER = ",";
    try
    {
        String line = "";
        //Create the file reader
        fileReader = new BufferedReader(new FileReader(fileToParse));

        //Read the file line by line
        int icount=0; //determine where to store the input
        int tcount=0; //determine where to store the target
        while ((line = fileReader.readLine()) != null)
        {
            //Get all tokens available in line
            String[] tokens = line.split(DELIMITER);
            for(String token : tokens)
            {
                //Print all tokens
                if (token.length() == 5)
                {
                        ***allInputs[icount]=token***;
                        System.out.println("Stored in all inputs:"+allInputs[icount]);
                        icount++;
                }
                else
                {
                    allTargets[tcount]=token;
                    System.out.println("Stored in all targets:"+allTargets[tcount]);
                    tcount++;
                }
                System.out.println("iCOUNT:"+icount);
                System.out.println("tCOUNT:"+icount);
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally
    {
        try {
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

allInputs[icount]=token行上,我得到以下错误

java.lang.ArrayIndexOutOfBoundsException: 32

提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    如果单元格的内容长度为5,则该行代码在每个单元格中运行一次。因为您的电子表格是32 x 2,所以最多可以有64个。但是你试图将它们放入一个长度为32的数组中,这当然超出了它的界限