我的问题是,如何将两个ArrayList相加?我要做的是导入两个单独的文件(包含2d数组)并将它们放入单独的arraylists中。从那里我试图将这两个数组列表相乘,然后让我的输出文件是输入的2d数组的乘积的二维数组。简而言之,我有两个输入文件(每个文件是一个单独的二维数组),我必须把这两个输入文件,并将它们相乘。我的输出文件应该是一个单独的2d数组。
到目前为止,我的代码如下:
package Matrix;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class Matrix {
public static void multiply(File input_file1, File input_file2, File output_file) {
try {
Scanner scanner = new Scanner(input_file1);
PrintWriter printer = new PrintWriter(output_file);
ArrayList<Integer> file1 = new ArrayList<Integer>();
while (scanner.hasNextInt()){
file1.add(scanner.nextInt());
}
scanner.close();
printer.close();
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Scanner scanner = new Scanner(input_file1);
PrintWriter printer = new PrintWriter(output_file);
ArrayList<Integer> file2 = new ArrayList<Integer>();
while (scanner.hasNextInt()){
file2.add(scanner.nextInt());
}
scanner.close();
printer.close();
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
//method that returns a double 2d matrix and takes two 2d matrices as parameters
public static double[][] multiply(double[][] A, double[][] B) {
//make sure the matrices are the same size
int mA = A.length;
int nA = A[0].length;
int mB = B.length;
int nB = B[0].length;
if (nA != mB) throw new RuntimeException("Matices are not the same");
//create a new matrix to hold answer
double[][] C = new double[mA][nB];
//loop and multiply
for (int i = 0; i < mA; i++)
for (int j = 0; j < nB; j++)
for (int k = 0; k < nA; k++)
C[i][j] += A[i][k] * B[k][j];
return C;
}
从ArrayList
转换为Array
ArrayList<ArrayList<String>> mainList = new ArrayList<ArrayList<String>>();
// populate this list here
//more code
// convert to an array of ArrayLists
ArrayList<String[]> tempList = new ArrayList<String[]>();
for (ArrayList<String> stringList : mainList){
tempList.add((String[])stringList.toArray());
}
//Convert to array of arrays - 2D array
String [][]list = (String[][])tempList.toArray();
算法的步骤基本上是: