gpt4 book ai didi

java - 从方法返回二维数组的正确语法

转载 作者:行者123 更新时间:2023-12-01 11:39:09 25 4
gpt4 key购买 nike

下面的两个方法(sortRows 和 sortColumns)应该返回一个由 rListcList 组成的二维数组,但我相信我声明它是错误的。

在主体的底部,我尝试打印它;该数组不会返回到 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;
}
}

最佳答案

Java 中的方法名称请使用驼峰命名法,这有助于区分类和方法。我相信错误是您没有在此处存储调用结果

SortRows(matrix); // <-- returns rTemp
SortColumns(matrix); // <-- returns cTemp

因为您使用(并在两者中返回一个new double[][])。你需要类似的东西

matrix = SortRows(matrix); // <-- sortRows(matrix);
matrix = SortColumns(matrix); // <-- sortColumns(matrix);

关于java - 从方法返回二维数组的正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29688782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com