该程序的目的是从文件中读取2d数组并进行转置。我完成了移调部分。如何将文件读入数组? 我需要使用的数组是5x5
import java.util.*;
import java.io.*;
public class prog464d{
public static void main(String args[]) throws IOException{
final int[][] original = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
for (int i = 0; i < original.length; i++) {
for (int j = 0; j < original[i].length; j++) {
System.out.print(original[i][j] + " ");
}
System.out.print("\n");
}
System.out.print("\n\n matrix transpose:\n");
// transpose
if (original.length > 0) {
for (int i = 0; i < original[0].length; i++) {
for (int j = 0; j < original.length; j++) {
System.out.print(original[j][i] + " ");
}
System.out.print("\n");
}
}
}
}
答案 0 :(得分:1)
java.io.File
,java.io.FileNotFoundException
和java.util.Scanner
。此外,这假设文本文件使用制表符作为其分隔符。如果文本文件是不同的维度,只需将ROWS
和COLS
更改为新数组的新维度
final int ROWS = 5;
final int COLS = 5;
int[][] nums = new int[ROWS][COLS];
// this is used only in java 7 (not java 6)
try (Scanner input = new Scanner(new File("filename.txt"))) {
int row = -1; // since we're incrementing row at the start of the loop
while(input.hasNext()) {
row++;
String[] line = input.nextLine().split("\t");
for(int col = 0; col < COLS; col++) {
try {
nums[row][col] = Integer.parseInt(line[col]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
} catch (FileNotFoundException e) {
// do something here
e.printStackTrace();
}
如果您使用的是Java 6,那么外部的try / catch就像:
try {
Scanner input = new Scanner(new File("filename.txt"));
// insert rest of code here
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
答案 1 :(得分:0)
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String row;
int i=0;
while( (row = br.readLine()) != null ) {
String[] tokens = row.split(" ");
int j =0;
for(String token : tokens) {
original[i][j++] = Integer.parseInt(token);
}
}
这假设您的文件类似于:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
row.split(&#34;&#34;)将返回一个字符串数组。 for循环将每个转换为int并将其存储为原始。