繁体   English   中英

Java do-while细节

[英]Java do-while detail

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

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加2只是为了测试。 错误使我的循环无限...

“;” 在评论的行上显示红色下划线(在Eclipse中)给我一个错误。

我谦卑地认为你错过了我的问题。 我不知道我的方法中的陈述是否正确(我正在研究它),但是我带来的是“;” 给我一个错误:“语法错误,插入”}“以完成MethodBody”。 如果这是由于我编码错误的逻辑,我道歉。 但我认为,相反,这表明我在do-while循环上做了一些语法错误。

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

  diagonal = true;

应该相反,你开始假设矩阵是身份,当你检查它不是真时返回false。

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

循环do-while是无限的,因为它永远不会得到matrizIdentidade(matriz)==true

尝试浏览矩阵的元素两次以检查对角矩阵的两个属性。 请试试这个:

public static boolean matrizIdentidade (int[][]m){

    boolean diagonal1 = false, diagonal2 = 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]==0)
                        diagonal1 = true;

        for (int i = 0; i < m.length; i++)
            for (int j = 0; j < m[0].length; j++)
                    if(i==j && m[i][j]==1)
                        diagonal2 = true;

        if(diagonal1 == true && diagonal2 == true ) return true
        else return false; 
}

如果问题与do-while的语法有关do-while请查看本文档的 Snippet:

       do {
            System.out.println("Count is: "
                               + count);
            count++;
        } while (count < 11);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM