gpt4 book ai didi

java文本到二维数组但打印IndexOutOfBounds错误

转载 作者:行者123 更新时间:2023-12-02 12:11:49 25 4
gpt4 key购买 nike

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

我想做的是为此数据集创建二维数组

二维数组应如下所示:

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放入matrix[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)

最佳答案

您需要为每个内部循环重置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更适合这个。

关于java文本到二维数组但打印IndexOutOfBounds错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46483827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com