来自txt文件和2d数组的数据,但显示arrayindexoutofbound错误

时间:2016-10-15 20:27:35

标签: java indexoutofboundsexception

当我运行时:

readData("data.txt")

我想使用此数据进行使用SVM的二进制分类。每个数据在最后一列都有一个类标签,所以我将它们放在另一个名为type的数组中,但是当我运行时,它会打印所有值,但它会显示

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at practice.A.readData(A.java:48)
    at practice.A.main(A.java:86)

我想知道造成这些异常的原因

public class A {
    static double [][] train,testdata,attributes;
    static int row,col,x;;
    static double [] type;
    static void readData(String fileName)  {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(fileName));
        String line;
        line = reader.readLine();
        for(row=1;reader.readLine()!= null;row++) {}    
        col= 1;
        for (int i=0;i<line.length();i++) {
            if(line.charAt(i)==',') 
                col++;
        }
        System.out.println(row);
        System.out.println(col);
         x=col-1;
        if(reader!=null) reader.close();
        attributes = new double[row][x];
        reader = new BufferedReader(new FileReader(fileName));
        String []words=new String[col];
        type =new double[row];
        for(int i=0; i<row;i++) {
            List<String> ob;
            ArrayList<String> w=new ArrayList<>();
            line = reader.readLine();
            words =line.split(",");
            if(!words[x].isEmpty())
                type[i]=Double.parseDouble(words[x]);
            ob=Arrays.asList(words);
            w.addAll(ob);
            System.out.println(Arrays.toString(words));
            w.remove(x);
            String [] new_words=new String[w.size()];
            new_words=w.toArray(new_words);
            for(int j=0;j<new_words.length;j++) {
                if(!new_words[j].isEmpty()){
                    attributes[i][j] = Double.parseDouble(new_words[j]);
                    System.out.print(attributes[i][j]+" ");
                }
            }
            w.clear();;
            System.out.println(type[i]);
        }
    } 
    catch (IOException e) {
        e.printStackTrace();
    }           
}

0 个答案:

没有答案