Reputation: 169
The below two methods(sortRows and sortColumns) are supposed to return a 2D array of rList
and cList
, but I believe I am declaring it wrong .
At the bottom of the main where I try to print it; the array is not returned to the main method.
In the main:
rList and cList cannot be resolved to a variable.
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;
}
}
Upvotes: 0
Views: 563
Reputation: 201447
Please use camelCase for method names in Java, that helps to distinguish classes from methods. I believe the bug is you aren't storing the result of the calls here
SortRows(matrix); // <-- returns rTemp
SortColumns(matrix); // <-- returns cTemp
because you use (and return a new double[][]
in both). You need something like
matrix = SortRows(matrix); // <-- sortRows(matrix);
matrix = SortColumns(matrix); // <-- sortColumns(matrix);
Upvotes: 1