【发布时间】:2013-01-23 19:26:41
【问题描述】:
下午好,
我目前正在阅读格式为
的文件5 5
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
进入二维数组。
第一行是二维数组的行长和列长(即 5x5)。
给定的输入值(值本身并不重要,只是它们是整数)需要读入二维数组,使得 array[0][0] = 0, array[0][1] = 0 等等。
我目前最讨厌的是,在第一行之后读取文件的内容并显示它到目前为止我所拥有的是,
public static void importFile(String fileName) throws IOException
{
int rows = 0;
int cols = 0;
int[][] numArray = null;
try {
int count = 0;
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null)
{
count++;
if (count == 1)
{
String[] tokenizer = line.split("\\s+");
rows = Integer.parseInt(tokenizer[0]);
System.out.println(rows);
cols = Integer.parseInt(tokenizer[1]);
System.out.println(cols);
numArray = new int[rows][cols];
} // end of if statement
else if(count > 1)
{
String[] tokenizer = line.split(" ");
for(int j = 0; j < tokenizer.length; j++)
{
numArray[rows][j] = Integer.parseInt(tokenizer[j]);
System.out.print(numArray[rows][j] + " ");
}
System.out.println("");
rows++;
} // end of else if
}// end of while loop
} //end of try statement
catch (Exception ex) {
System.out.println("The code throws an exception");
System.out.println(ex.getMessage());
}
System.out.println("I am printing the matrix: ");
for (int i = 0; i < rows; i++) {
for(int j=0; j < cols; j++)
System.out.print(numArray[i][j] + " ");
System.out.println("");
}
} // end of import file
} // 类结束 输出如给定
Please enter the file you'd like to use:
data4.txt
5
5
The code throws an exception
5
I am printing the matrix:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
【问题讨论】:
-
你永远不会写入 numArray
-
@sdir。嗯,这不是主要问题。整数数组无论如何都会将
0作为默认值。我知道这是错误的,我们需要从文件中填充值。但问题出在其他原因。 -
@Only1Realme.. 问题是,您将
5读取为字符'5',然后将其存储在整数变量中。因此,您不会将5视为int,而是ASCII Code,即53。除了这个问题,你真的让你的工作变得复杂了。遵循@jlordo 的答案中所示的方法。 -
用
e.printStackTrace();替换System.out.println(e.getMessage());并显示输出。
标签: java arrays bufferedreader