2016-05-16 9 views
-2

warum i schreiben müssen:Java - ein Stück Code in Array Verständnis

mat.length-1 

in der zweiten für die Schleife (die Schleife er alle Bedingungen).

die Schleife:

for (int i = 0; i < mat.length-1; i++) { 
     for (int j = 0; j < mat.length-1; j++) { 
      if (i == j) { 
       j++; 
       if (i == mat.length - 1 && j == mat.length - 1) { 
        break; 
       } 
      } 
      if (i != j && mat[i][j] == mat[j][i]) { 
       flag = true; 

      } else { 
       flag = false; 
       if (flag == false) { 
        stop = 1; 
        i = mat.length - 1; 
       } 
      } 
     } 

    } 

Checking program applies

komplette Code:

public class test { 
public static void main(String[] args) { 

    //int[][] mat = { { 9, 2, 4 }, { 2, 9, 7 }, { 4, 7, 9 } }; 
    int[][]mat = { { 9, 2, 3, 4}, 
        { 2, 9, 6, 3}, 
        { 3, 6, 9 ,2}, 
        { 4, 3, 2 ,9}}; 

    boolean flag = true; 
    int stop = 0; 

    for (int i = 0; i < mat.length; i++) { 
     for (int j = 0; j < mat.length; j++) { 
      System.out.print("[" + mat[i][j] + "]"); 
     } 
     System.out.println(); 
    } 
    for (int i = 0; i < mat.length-1; i++) { 
     for (int j = 0; j < mat.length-1; j++) { 
      if (i == j) { 
       j++; 
       if (i == mat.length - 1 && j == mat.length - 1) { 
        break; 
       } 
      } 
      if (i != j && mat[i][j] == mat[j][i]) { 
       flag = true; 

      } else { 
       flag = false; 
       if (flag == false) { 
        stop = 1; 
        i = mat.length - 1; 
       } 
      } 
     } 

    } 

    if (stop == 1) { 
     System.out.println("Not first folded matrix"); 
    } else { 
     System.out.println("First folded matrix"); 
    } 

} 
} 

diese Arbeit ist, aber wenn ich es ändern zu

mat.length 

Es funktioniert nicht Wenn ich ein negatives schreibe, stoppt es die Schleife des i, bevor es das Ende des Arrays erreicht. Kann Erklärung?

+0

Sie wahrscheinlich codieren, müssen 'for (int i = 0; i jr593

Antwort

0

In Ihrem Code dienen diese Zeilen keinem Zweck, da i und j in Ihrem Code niemals gleich (mat.length-1) sein würden.

if (i == mat.length - 1 && j == mat.length - 1) { 
    break; 
} 

Ändern Sie Ihren Code:

for (int i = 0; i < mat.length; i++) { 
     for (int j = i+1; j < mat.length; j++) { 
      if (mat[i][j] != mat[j][i]) { 
       flag = false; 
       j = mat.length; 
       i = mat.length; 
      } 
     } 
    } 

    if (flag == false) { 
     System.out.println("Not first folded matrix"); 
    } else { 
     System.out.println("First folded matrix"); 
    } 
+0

danke effektiv – acvbfd123