Java 如何将文件读入二维数组
下午好 我目前正在读一个文件的格式Java 如何将文件读入二维数组,java,arrays,bufferedreader,Java,Arrays,Bufferedreader,下午好 我目前正在读一个文件的格式 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 转换为二维数组 第一行是2D数组的行长和列长(即5x5) 前几行是给定的输入值(值本身并不重要,只是它们是整数),需要将这些值读入2D数组,以便数组[0][0]=0,数组[0][1]=0等 我现
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
转换为二维数组
第一行是2D数组的行长和列长(即5x5)
前几行是给定的输入值(值本身并不重要,只是它们是整数),需要将这些值读入2D数组,以便数组[0][0]=0,数组[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
我认为你把事情复杂化了。如果可以假定文件格式始终正确,则可以安全地使用
String[] tokenizer = line.split(" "); // you have this line of code already.
rows = Integer.parseInt(tokenizer[0]);
cols = Integer.parseInt(tokenizer[1]);
这将解决你阅读第一行的问题
您的问题是这行代码:
rows = tempLine;
将值设置为tempLine
(int tempLine=line.charAt(i);
)的方式就是获取int
字符的值。char
'5'
的int
值不是5,而是53,因为这是字符'5'
的ASCII码 对于第一行:
if (count == 1) {
String[] tokenizer = line.split(" ");
row=Integer.parseInt(tokenizer[0]);
col=Integer.parseInt(tokenizer[1]);
System.out.println("There are " + cols + " colums");
numArray = new int[row][col];
} // end of if statement
用于填充数组
String[] tokenizer = line.split(" ");
for(int j=0;j<col;j++){
numArray[0][j]=Integer.parseInt(tokenizer[j]); //fill the array from tokenizer
}
String[]tokenizer=line.split(“”);
对于(int j=0;j我们在我的另一个答案下进行了扩展讨论。因为您的代码显示您已经尝试过(并且非常接近),我将为您的问题发布一个健壮的解决方案。我完全重写了它,因为您的程序有许多小错误,要详细说明每一个错误可能需要更多的工作。以下方法将读取指定格式的文件并返回结果int[][]
。如果文件中有错误,该方法将告诉您;)
publicstaticint[]importFile(字符串文件名)引发IOException{
BufferedReader reader=新的BufferedReader(新文件读取器(文件名));
int[][]努马拉伊;
字符串行=reader.readLine();
如果(行==null){
抛出新的IllegalArgumentException(“没有第1行”);
}
字符串[]维度=行。拆分(\\s+);
试一试{
int rows=Integer.parseInt(维度[0]);
int cols=Integer.parseInt(维度[1]);
//TODO:检查是否存在负值。
numArray=新整数[行][列];
}捕获(数字格式){
抛出新的IllegalArgumentException(“文件的第一行必须是‘rows cols’”);
}
int行=0;
while((line=reader.readLine())!=null&&rownumArray[row].length){
抛出新的IllegalArgumentException(“矩阵行中提供的值太多”+行);
}
//to less值将用0填充。如果您不希望这样做
//您必须取消注释接下来的3行。
//if(tokens.length
您永远不会向numArray@sdir. 嗯,这不是主要问题。整数数组将以0
作为默认值。我知道这是错误的,我们需要从文件中填充值。但问题是因为别的原因。@onlyrealme。。问题是,您正在将5
读取为字符'5'
,然后将其存储在整数变量中。因此,您将不会得到5
作为int
,而是ASCII代码,即53
。除了这个问题,你真的让你的工作变得复杂。遵循@jlordo的答案中所示的方法。replaceSystem.out.println(e.getMessage())代码>带有e.printStackTrace()代码>并显示输出。这解决了我在第一行遇到的问题,现在我将研究如何通过附加的代码更改来读取文件的内容。谢谢你的帮助rows=Integer.parseInt(标记器[0]);cols=Integer.parseInt(标记器[1])当我尝试打印System.out.println(行)时,code>落入try的catch语句中代码>System.out.println(cols)代码>它产生所述错误。您的错误表示输入为“5,5”
。在你的问题中,你说输入是“5”
。我的答案是输入“5”
。如果希望版本带有逗号,则必须使用String[]tokenizer=line.split(“,”)代码>。你必须严格遵守你的规格。您发布的文件格式不包含逗号。您的错误消息显示有一个逗号。另外,将其写入catch块:e.printStackTrace()
请输入您要使用的文件:data4.txt test1 test2 java.lang.NumberFormatException:输入字符串:java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)java.lang.Integer.parseInt(Integer.java:492)java.lang.Integer.parseInt(Integer.java:527)at(load.java:44)
String[] tokenizer = line.split(" ");
for(int j=0;j<col;j++){
numArray[0][j]=Integer.parseInt(tokenizer[j]); //fill the array from tokenizer
}
public static int[][] importFile(String fileName) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
int[][] numArray;
String line = reader.readLine();
if (line == null) {
throw new IllegalArgumentException("There was no 1st line.");
}
String[] dimensions = line.split("\\s+");
try {
int rows = Integer.parseInt(dimensions[0]);
int cols = Integer.parseInt(dimensions[1]);
// TODO: check for negative values.
numArray = new int[rows][cols];
} catch (NumberFormatException e) {
throw new IllegalArgumentException("First line of file has to be 'rows cols'");
}
int row = 0;
while ((line = reader.readLine()) != null && row < numArray.length) {
String[] tokens = line.split("\\s+");
if (tokens.length > numArray[row].length) {
throw new IllegalArgumentException("Too many values provided in matrix row " + row);
}
// to less values will be filled with 0. If you don't want that
// you have to uncomment the next 3 lines.
//if (tokens.length < numArray[row].length) {
// throw new IllegalArgumentException("Not enough values provided in matrix row " + row);
//}
for(int column = 0; column < tokens.length; column++) {
try {
int value = Integer.parseInt(tokens[column]);
numArray[row][column] = value;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Non numeric value found in matrix row " + row + ", column " + column);
}
}
row++;
}
if (line != null) {
// there were too many rows provided.
// Superflous ones are ignored.
// You can also throw exception, if you want.
}
if (row < numArray.length) {
// There were too less rows in the file. If that's OK, the
// missing rows will be interpreted as all 0.
// If that's OK with you, you can comment out this whole
// if block
throw new IllegalArgumentException("Expected " + numArray.length + " rows, there only were " + row);
}
try {
reader.close(); // never forget to close a stream.
} catch (IOException e) { }
return numArray;
}