此代码的目标是将单维数组乘以2维数组。下面的产品数组是我试图获取并打印
我面临的错误是方法 outputArray ,
示例输出:
arrayOne[] = 2,4
arrayTwo[][] = 2,4,6
8,10,12
productArray = (2*2 + 4*8) , (2*4 + 4*10) , (2*6 + 4*12)
public static void main(String[] args) {
// TODO code application logic here
description();
int arrayLength = getLength();
double[] arrayOne = getArrayOne(arrayLength);
int numCol = getNumColumn();
int rows = numCol;
double[][] arrayTwo = getArrayTwo(rows, numCol);
outputArray(arrayOne, arrayTwo, rows, numCol);
}
public static int getLength() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the length of the first array");
int length = input.nextInt();
return length;
}
public static double[] getArrayOne(int length) {
Scanner input = new Scanner(System.in);
double array[] = new double[length];
System.out.println("Please enter the contents of the first array: ");
for (int i = 0; i < length; ++i) {
array[i] = input.nextDouble();
}
return array;
}
public static int getNumColumn() {
Scanner input = new Scanner(System.in);
int numcolumn;
System.out.println("Enter the number of columns of the 2D array: ");
int numColumn = input.nextInt();
return numColumn;
}
public static double[][] getArrayTwo(int rows, int columns) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the contents of the second array: ");
double array[][] = new double[rows][columns];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
array[i][j] = input.nextDouble();
}
}
return array;
}
public static void outputArray (double[] arrayOne, double[][] arrayTwo, int rows, int column) {
double sum = 0;
Double productArray[] = new Double[column];
for (int i = 0; i < rows; i++){
sum += arrayOne[i] * arrayTwo[i][0];
productArray[arrayOne.length] = sum;
}
for (int i = 0; i < productArray.length; i++){
System.out.println(" " + productArray[i]);
}
}
public static void description() {
System.out.println("This program will multiply 2 one dimension arrays of any length. The length and the contents of the arrays is entered from the keyboard.");
}
答案 0 :(得分:2)
在outputArray()
中,你以错误的方式嵌套循环;你应该在你的列循环中有行循环。它应该是:
for (int k = 0; k < column; k++) {
int sum = 0;
for (int j = 0; j < rows; j++) {
sum += arrayTwo[j][k] * arrayOne[j];
}
productArray[k] = sum;
}
打印出数组[36.0,48.0,60.0]