gpt4 book ai didi

java - 文件中的二维字符数组

转载 作者:行者123 更新时间:2023-12-01 04:13:37 27 4
gpt4 key购买 nike

我正在尝试从文件中读取字符串,提取单个字符并使用这些字符填充二维字符数组。到目前为止,除了填充数组之外,我已经能够完成所有操作。我不断收到线程“main”java.lang.ArrayIndexOutOfBoundsException 中的异常:错误消息。任何帮助,将不胜感激。这是我第一次使用二维数组。谢谢。这是test.txt的内容。每个词换行。前 2 个整数是数组的维度4 4文件和一些信息

public class acsiiArt 
{

public static void main(String[] args) throws IOException
{
File file = new File("test.txt");
Scanner inputFile = new Scanner(file);
int x = inputFile.nextInt();
int y = inputFile.nextInt();
while (inputFile.hasNext())
{
char [][] array = new char [x][y];

//char c = words.charAt(i);
for (int row =0; row<x;row++)
{
for (int col =0; col<y;col++)
{
String words = inputFile.nextLine();
for (int i=0; i<words.length(); i++)

array[x][y]=words.charAt(i);
}
}
}

}
}

最佳答案

for (int row =0; row<x;row++)
{
for (int col =0; col<y;col++)
{
String words = inputFile.nextLine();
for (int i=0; i<words.length(); i++)

array[x][y]=words.charAt(i);
}
}

array 中的索引总数为 x * y。下面,您将填写所有可能的索引

for (int row =0; row<x;row++)
{
for (int col =0; col<y;col++)

所以当你添加这个时:

for (int i=0; i<words.length(); i++)

您乘以另一个因子words.length。因此,您需要 x * y * Words.length 个索引,但只有 x * y。这就是为什么您会收到 ArrayIndexOutOfBoudsException

关于java - 文件中的二维字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19649807/

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