java文本到2d数组但打印IndexOutOfBounds错误

时间:2017-09-29 07:26:20

标签: java

txt文件中的数据看起来

1.1, 2.2, 3.3, 4.4, 5.5
1.1, 3.3, 5.5, 7.7, 9.9
1, 4.4, 5, 100, 5050
1010, 2, 3, 4, 55

我要做的是为这个数据集创建二维数组

2-D数组应如下所示:

1.1   2.2   3.3   4.4   5.5
1.1   3.3   5.5   7.7   9.9
...
...
1010   2   3   4   55

代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class QuestionB
{
    public QuestionB(String fileName)
    {
        try
        {
            readFile(fileName);
        }
        catch(IOException e)
        {
        }
    }

    public static void main(String[] args)
    {
        QuestionB questionB = new QuestionB("wine.data");


    }

    public void readFile(String fileName) throws IOException
    {
        InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName);

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String line;

        int x = 0;
        int y = 0;

        String matrix[][] = new String[178][13];

        int test = 1;
        while( (line = bufferedReader.readLine() ) != null)
        {
            String values[] = line.split(",");  

            for(String str : values)
            {
                //System.out.println("test: " + test++);
                //System.out.println(str);
                matrix[x][y] = str;

                //System.out.print(matrix[x][y] + " ");

                y = y + 1;
            }

            x = x + 1;

            //System.out.println("");

        }
    }
}

当我打印str时,它会正确打印所有值,但是当我将str放入矩阵[x] [y]时,它会给出indexoutofbound错误

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 13
    at QuestionB.readFile(QuestionB.java:48)
    at QuestionB.<init>(QuestionB.java:12)
    at QuestionB.main(QuestionB.java:21)

2 个答案:

答案 0 :(得分:1)

您需要为每个内循环重置y

while( (line = bufferedReader.readLine() ) != null)
    {
        y = 0;   //RESET y

        String values[] = line.split(",");  
        for(String str : values)
        {
            matrix[x][y] = str;
            y = y + 1;
        }
        x = x + 1;
    }

注意:正如dpr所述,如果您的文件不正确(每行超过13个元素或超过178行),这仍然会失败。ArrayList对此更好。

答案 1 :(得分:0)

如果您不想使用像ArrayList这样的Collection,那么Jagged Array是您的最佳选择。

String matrix[][] = new String[max][];

其中max是变量,并将max指定为可以存储总行数的值。

并且每次从文件中读取下一行时,也需要指定y = 0,即在while循环开始时。