我正在尝试编写一个方法,在该方法中我需要创建一个泛型类型 T 的临时变量 sum。但是,我收到错误“局部变量 sum 可能尚未初始化”。如何初始化通用变量?我无法将其设置为 0 或 0.0,而且我无法在任何地方找到有关如何处理此问题的信息。这是我正在使用的代码部分:
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; …Run Code Online (Sandbox Code Playgroud) 我编写了这个程序来创建一个列表,然后使用该列表来填充一个数组.然后magicCheck方法检查矩阵是否是魔方.我最初把它写成一个大小为4x4的定义矩阵.当我这样做时,一切都很好.现在我想让用户决定数组的大小(nxn).添加代码以提示用户输入n,并基于nxn而不是4x4创建矩阵后,我的printMatrix方法已停止工作.
当我按原样运行程序,输入n = 2,first = 2,diff = 2,这是我得到的输出:"输入数组的大小(格式为nxn),n:4先输入,差异:2 2
这不是一个神奇的广场."
谁能告诉我为什么printMatrix不再有效?另外,我知道我的magicCheck方法对循环很邋and,我确信有更好的方法来处理它,但我仍然非常新,并将它拼凑在一起以任何方式让它工作.请温柔:]
这是我的代码:
import java.util.*;
public class MagicSquare
{
static int row, col, n;
static final int rows = n;
static final int columns = n;
static final int listSize = (n*2);
static Scanner console = new Scanner (System.in);
public static void createArithmeticSeq(int [] list)
{
//prompt user for array size
System.out.println("Enter size of array (in form nxn), n:");
n = console.nextInt();
int first;
int diff;
//prompt user for first and …Run Code Online (Sandbox Code Playgroud)