2d字符数组 [英] 2d char array from a file
问题描述
我想从文件中读取一个字符串,提取单个字符,并使用这些字符填充一个2D字符数组。到目前为止,我已经能够做的一切,除了填充数组。我不断得到一个异常在线程mainjava.lang.ArrayIndexOutOfBoundsException:错误消息。任何帮助将不胜感激。这是我第一次使用2D数组。谢谢。
下面是test.txt的内容。每一个字在一个新行。前2个整数是数组的维数
4 4
FILE
WITH
SOME
INFO
I am trying to read in a string from a file, extract individual characters and use those characters to fill a 2D char array. So far I have been able to do everything except fill the array. I keep getting an Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: error message. Any help would be appreciated. This is my first time working with 2D arrays. Thanks. Here are the contents of the test.txt. Each word on a new line. The first 2 integers are the dimensions of the array 4 4 FILE WITH SOME INFO
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
。下面是填充所有可能的索引
The total number of indices in array
is x * y
. Below, you are filling all the possible indices
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
you multiplying another factor words.length
. So you need x * y * words.length
number of indices, but you only have x * y
. Thats why you're getting ArrayIndexOutOfBoudsException
这篇关于2d字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!