![](/img/trans.png)
[英]Read file.txt and take the int value in it then put them into a 2D array for sudoku
[英]How to read int numbers (matrix) from file.txt and add to array?
我想將兩個矩陣相乘。 我有 2 個帶有 2 個不同整數(矩陣)的文件。
file1.txt
4 3 4 6
-1 10 4 -1
4 7 2 -8
file2.txt
3 0 0
0 3 0
0 0 3
0 2 4
怎樣才能把這些文件分別讀成一個二維數組,方便相乘。 我有一個代碼,其中在開頭指示了矩陣的大小,但是如果矩陣的大小可能不同怎么辦? 這是我給定大小的代碼:
public static void main(String[] args) throws IOException {
try {
Scanner input = new Scanner(new File(file1.txt));
int m = 3; // I need the size for random matrix
int n = 5; // I need the size for random matrix
int[][] a = new int[m][n];
while (input.hasNextLine()) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
try{
a[i][j] = input.nextInt();
System.out.println("number is "+ a[i][j]);
}
catch (java.util.NoSuchElementException e) {
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
如果矩陣的維度已知,最好實現一個單獨的方法將文件讀入矩陣:
public static int[][] readFileWithMatrix(String filename, int rows, int cols) throws Exception {
int[][] arr = new int[rows][cols];
try (Scanner input = new Scanner(new File(filename))) { // use try-with-resources to close Scanner
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = input.nextInt();
}
}
}
return arr;
}
那么使用這種方法會更簡單:
int[][] arr3x4 = readFileWithMatrix("file1.txt", 3, 4);
int[][] arr4x3 = readFileWithMatrix("file2.txt", 4, 3);
//... do matrix multiplication
在這里嘗試下面的代碼,假設它只包含矩陣元素並將其存儲到一個動態二維數組中a
例如,列表列表,它從文件中獲取所有輸入。 首先,我讀取文件的第一行並從中取出所有數字,這給了我矩陣的總列數。 接下來,我繼續閱讀輸入行,直到文件末尾擴展矩陣的行a
public static void main(String[] args) throws IOException {
try {
Scanner input = new Scanner(new File(file1.txt));
List<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
int row=0;
String cols[] = input.nextLine().split(" ");
a.add(row, new ArrayList<Integer>());
for (int j = 0; j < cols.length; j++) {
try {
a.get(row).add(Integer.parseInt(cols[j]));
} catch (Exception e) {
}
}
row++;
while (input.hasNextLine()) {
a.add(row, new ArrayList<Integer>());
for (int j = 0; j < cols.length; j++) {
try {
a.get(row).add(input.nextInt());
} catch (java.util.NoSuchElementException e) {
}
}
row++;
}
System.out.println("Rows: "+row+" Columns: "+cols.length);
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < a.get(i).size(); j++) {
System.out.println("Number is "+ a.get(i).get(j));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
演示代碼在這里: https://ideone.com/ZEcgPR#stdin
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.