[英]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.