以下两种方法(sortRows和sortColumns)应该返回rList
和cList
的2D数组,但我相信我声明它错了。
在我尝试打印的主要底部;数组不会返回到main方法。
主要:
rList和cList无法解析为变量。
public class Markov {
public static void main(String[] args) {
double[][] matrix = new double[3][3];
int r, c;
double val;
String inputV;
// asks user for values
for (c = 0; c < 3; c++)
for (r = 0; r < 3; r++) {
inputV = JOptionPane.showInputDialog("Enter value for row # " + (r + 1) + " , column # " + (c + 1));
val = Double.parseDouble(inputV);
matrix[c][r] = val;
}
if (ValidateMarkov(matrix) == false) {
System.out.println(" Invalid Markov, values must be postive, colummn values must sum to 1.0 ");
} else {
System.out.println("Valid Markov");
}
SortRows(matrix);
SortColumns(matrix);
// Prints the matrices
for (r = 0; r < 3; r++) {
System.out.println();
for (c = 0; c < 3; c++) {
System.out.print(" " + matrix[r][c] + " ");
}
}
for (r = 0; r < 3; r++) {
System.out.println();
for (c = 0; c < 3; c++) {
System.out.print(" " + rTemp[r][c] + " ");
}
}
for (r = 0; r < 3; r++) {
System.out.println();
for (c = 0; c < 3; c++) {
System.out.print(" " + cTemp[r][c] + " ");
}
}
}
public static boolean ValidateMarkov(double[][] n) {
double sum;
for (int c = 0; c < 3; c++) {
sum = 0;
for (int r = 0; r < 3; r++) {
if (n[c][r] < 0) {
return false;
}
sum += n[c][r];
}
if (sum != 1) {
return false;
}
}
return true;
}
public static double[][] SortRows(double[][] m) {
int r, c;
double[][] rTemp = new double[3][3];
for (r = 0; r < 2; r++)
for (c = 0; c < 2 - c; c++)
if (m[r][c] > m[r][c + 1]) {
rTemp[r][c] = m[r][c];
m[r][c] = m[r][c + 1];
m[r][c + 1] = rTemp[r][c + 1];
}
return rTemp;
}
public static double[][] SortColumns(double[][] n) {
int r, c;
double[][] cTemp = new double[3][3];
for (c = 0; c < 2; c++)
for (r = 0; r < 2 - r; r++)
if (n[c][r] > n[c][r + 1]) {
cTemp[c][r] = n[c][r];
n[c][r] = n[c][r + 1];
n[c][r + 1] = cTemp[c][r + 1];
}
return cTemp;
}
}
答案 0 :(得分:1)
请使用camelCase作为Java中的方法名称,这有助于区分类和方法。我相信这个错误是你不是在这里存储调用的结果
SortRows(matrix); // <-- returns rTemp
SortColumns(matrix); // <-- returns cTemp
因为您使用(并在两者中都返回new double[][]
)。你需要像
matrix = SortRows(matrix); // <-- sortRows(matrix);
matrix = SortColumns(matrix); // <-- sortColumns(matrix);