[Java] Multiply elements of an array
Hello. As the title says, I'm making a class that could Multiply the elements of an array capturing from the Keyboard. I've mostly done (so I think) but I got 3 problems that are giving me a headache.
Here's the code.
Code:
import java.io.*;
public class Array{
//Implements methods for multiplying elements in an array
//Ronnye Gutierréz - 2011
private static float[][] M1; //Array 1
private static float[][] M2; //Array 2
private static float[][] R; //Resulting Array
private static int N = 2; //Order of Arrays
public static void main(String args[]) throws IOException{
M1 = new float[N][N];
M2 = new float[N][N];
R = new float[N][N];
System.out.print("Capture of values\n");
System.out.print("Values for Array 1\n");
(M1);
System.out.print("\nValues for Array 2\n");
EnterData(M2);
System.out.println("Capture complete");
System.out.print("\nArray 1:\n");
Print(M1);
System.out.print("\nArray 2:\n");
Print(M2);
Multiply();
System.out.print("\nResulting Array:\n");
Print(R);
System.out.println();
}
//Method to load the data into arrays
public static void IngresaDatos(float m[][]) throws IOException{
String cad; //To store keyboard capture
//Set LeeBuf to capture Keyboard
BufferedReader LeeBuf = new BufferedReader(new InputStreamReader(System.in));
//Fill array
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++){
System.out.print("Enter Value [" + (i + 1) + "," + (j + 1) + "]: ");
cad = LeeBuf.readLine(); //Read line and stores it in cad
m[j] = Float.parseFloat(cad); //Convert cad to float and store it in m[i, j]
} //Close for
} //Close EnterData
//Method which calculates the multiplication of two matrices
public static void Multiply()
{
float sum;
for(int i = 0; i < N; i++){ //Start cycle lines
for(int j = 0; j < N; j++){ //Start cycle columns
sum = 0;
for(int k = 0; k < N; k++){ //Cycle internal for summations
sum += M1[k] * M2[k][j];
}
R[j] = sum;
}
}
}
public static void Imprime(float m[][])
{
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
System.out.print(m[j] + " ");
}
System.out.print("\n");
}
}
}//Fin clase Matriz
And here are the lines & errors.
Code:
m[j] = Float.parseFloat(cad)
Type mismatch: cannot conver from fload to fload[]
sum += M1[k] * M2[k][j];
The operator * is undefined for th eargument type(s) float[], float
R[j] = sum;
Type mismatch: cannot conver from fload to fload[]
I would appreciate it if someone could help me. I'm sorry if I'm asking a lot, but I have nothing to lose.
Re: [Java] Multiply elements of an array
You're trying to assign a float value to a member of a jagged array, which is an array. You need to provide both indices, not just one.
ie. m[i][j] = blah; instead of m[i] = blah;
The same goes for the multiplication issue... You can't multiply a value by an array.