Java do-while 详细信息

标签 java matrix do-while

我的代码出错了,但我不知道如何改正它:

public class Cenas {
public static void main(String[] args) {
    //gera matrizes de tamanho aleatório com uns e zeros
    int a = 2;//(int)(Math.random() *3) + 1;
    int b  = 2;//(int)(Math.random() *3) + 1;
    int[][]matriz = new int [a][b];
    do{
        for (int i=0; i<a; i++) {
            for (int j=0; j<b; j++) {
                matriz[i][j] = (int) Math.round(Math.random());
                System.out.print(matriz[i][j] + " ");
            }
            System.out.println("");
        }
    }while(matrizIdentidade(matriz)==true); //the error is in here!!! the ";"


public static boolean matrizIdentidade (int[][]m){
    boolean diagonal = false;
    if (m.length==m[0].length) //matriz.Testada[0] é o comprimento da matriz
        for (int i = 0; i < m.length; i++)
            for (int j = 0; j < m[0].length; j++)
                if(i==j && m[i][j]==1)
                    if(i!=j && m[i][j]==0)
                        diagonal = true;
    return diagonal;
}
}

它生成随机矩阵并告诉我它们是否是单位矩阵。我将 System.out.print 和 2 x 2 尺寸放在测试中。该错误使我的循环无限...

";"在评论的行上出现红色下划线(在 Eclipse 中)给我一个错误。

我谦虚地认为你错过了我的问题。我不知道我的方法中的陈述是否正确(我正在努力),但让我来到这里的是“;”给我一个错误:“语法错误,插入“}”以完成 MethodBody”。如果那是由于我的逻辑编码错误,我深表歉意。但我认为,相反,这表明我在 do-while 循环中犯了一些语法错误。

最佳答案

您仅由最后一个成员定义返回值

  diagonal = true;

应该相反,你开始假设矩阵是恒等式,当你检查它不是真的时返回假。

if((i==j && m[i][j]!=1) || (i!=j && m[i][j]!=0)) {
   // this is not an identity matrix, so you can stop
   return false;
}

如果循环结束,矩阵就是恒等式,所以返回 true

关于Java do-while 详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14172919/

相关文章:

java do while循环不断重复,我不明白为什么

python - 生成随机转移概率矩阵python

java - 如何使用JSP翻页保留参数

java - 启动期间为空颜色

java - 如何在 spreadsheetview controlsfx 中旋转单元格值?

c++ - 试图使矩阵类工作

java - 如何将单维索引转换为多维数组中的相应索引?

c++ - if (!(cin >> variableName)) 在此循环中的相关性是什么

c - Do while 循环给出意外的输出

java - 如何在运行时确定泛型对象的声明类型?