こんにちは、
私は現在、次の形式のファイルの読み取りに取り組んでいます
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配列に。
最初の行は、2D配列(つまり、5x5)の行の長さと列の長さです。
後続の行には、array [0] [0] = 0、array [0] [1] = 0などの2D配列に読み込む必要のある入力値(値自体は整数であるだけでなく重要です)が与えられます。 。
私が現在嫌いなのは、最初の行の後にファイルの内容を読み取り、それを表示することです。これまでのところ、
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