2014-02-25 23 views
2

我想創建這種形狀不同:如何使開始和一些行結束是在Java

<>()<>()<> 
()<>()<>() 
<>()<>()<> 
()<>()<>() 
<>()<>()<> 

如果我使用任何偶數n個都數是好的,但,當我使用奇數所有行的起始數字都是相同的。

這是我的代碼:

int n = 5, line = 1, colomn = 1; 

    for (int i=0; i< (n*n); i++){ 

     if ((line % 2) == 0){ 
      System.out.print((((i%2) == 0) ? "()" : "<>")); 
     }else{ 
      System.out.print((((i%2) == 1) ? "()" : "<>")); 
     } 

     if (colomn == n){ 
      colomn = 1; 
      line++; 
      System.out.println(); 
     } else { 
      colomn++; 
     } 
    } 

謝謝:)

+1

可以只使用是System.out.print'((線+柱)%2 == 0?「()」:「<>」);' –

回答

0

使用colomn代替我:

if ((line % 2) == 0){ 
     System.out.print((((colomn%2) == 0) ? "()" : "<>")); 
    }else{ 
     System.out.print((((colomn%2) == 1) ? "()" : "<>")); 
    } 
+0

@ user3197337該代碼可以進一步簡單化。看到我的答案;-) – TheConstructor

2

n = 3的第一行I = 0,1,2第二個i = 3,4,5第三個i = 6,7,8。同一行中的i = 0和i = 3具有不同的模式,但由於它們處於不同行中,所以第二個條件翻轉該模式。

或者切換icolomn內部印刷或使用

int n = 5; 

    for (int line = 0; line < n; line++) { 

     for (int column=0; column < n; column++){ 

      if ((line + column) % 2 == 0){ 
       System.out.print("<>"); 
      }else{ 
       System.out.print("()"); 
      } 
     } 
     System.out.println(); 
    } 
0

又一解決方案:

int n = 5, line = 0; 
    for (int i = 1; i <= n*n; i++){ 
     String str; 

     if (n % 2 == 0 && line % 2 == 0) 
      str = i % 2 == 0 ? "<>" : "()"; 
     else 
      str = i % 2 == 0 ? "()" : "<>"; 

     System.out.print(str); 

     if (i % n == 0) { 
      System.out.println(); 
      line++; 
     }  
    }