【发布时间】:2013-11-08 02:40:24
【问题描述】:
我正在尝试从文件中读取字符串,提取单个字符并使用这些字符填充 2D 字符数组。到目前为止,除了填充数组之外,我已经能够做所有事情。我在线程“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);
}
}
}
}
}
【问题讨论】:
-
请在test.txt中发布一些内容。实际上,我认为有2个地方需要修改。 1.关于2 for循环。使用变量 row 和 col。你为什么不使用它们。将 array[x][y]=words.charAt(i) 更改为 array[row][col]=words.charAt(i); 2.将以下代码放在while循环之外。字符 [][] 数组 = 新字符 [x][y];
-
4 4 FILE WITH SOME INFO 这里是内容。每个单词是一个新行,两个整数是数组的维度。
标签: java char multidimensional-array