I am trying to write a method in which I need to create a temporary variable sum, general type T. Nevertheless, I get the error "Local variable sum may not have been initialized." How to initialize a shared variable? I cannot set it to 0 or 0.0, and I cannot find information on how to handle this. Here is the part of the code I'm working with:
public Matrix<T,A> multiply(Matrix<T,A> right) throws MatrixException { Matrix<T,A> temp = new Matrix<T,A>(arithmetics, rowSize, columnSize); T sum, product; if (rowSize != right.columnSize) throw new MatrixException("Row size of first matrix must match column size " + "of second matrix to multiply"); setup(temp,rowSize,columnSize); for (int i = 0; i < rowSize; i++){ for (int j = 0; j < right.columnSize; j++) { product = (arithmetics.multiply(matrix[i][j] , right.matrix[j][i])); sum = arithmetics.add(product, sum); temp.matrix[i][j] = sum; } } return temp; }
I'm not sure this will help clarify, but here is my Arithmetics interface:
public interface Arithmetics<T> { public T zero(); public T add( T a, T b ); public T subtract( T a, T b); public T multiply (T a, T b); public T parseString( String str ); public String toString( T a ); }
And here is one of my classes, DoubleArithmetics, just to show how I implement the interface:
public class DoubleArithmetics implements Arithmetics<Double> { protected Double value; public Double zero() { return new Double(0); } public Double add( Double a, Double b ) { return new Double(a.doubleValue()+b.doubleValue()); } public Double subtract (Double a, Double b) { return new Double(a.doubleValue()-b.doubleValue()); } public Double multiply (Double a, Double b) { return new Double(a.doubleValue()*b.doubleValue()); } public Double parseString( String str ) { return Double.parseDouble(str); } public String toString( Double a ) { return a.toString(); } }