2016-08-02 61 views
-1

在二維數組中,我們可以生成n * n矩陣。以及如何將數字替換爲0的替換矩陣中。如何在二維數組中生成0的樓梯案例?

public static void main(String[] args) { 
     int rows = 8; 
     int coulmns = 4; 
     int array; 
     for (int i = 1; i < rows; i++) { 
      for (int j = 1; j < coulmns; j++) { 

       System.out.print(i*j+" "); 
      } 
      System.out.println(""); 
     } 
    } 

} 

輸出:

1 2 3 
2 4 6 
3 6 9 
4 8 12 
5 10 15 
6 12 18 
7 14 21 

我怎麼能輸出的形式取代0在樓梯的情況下:

1 2 (0) 
2 (0) 6 
(0) 6 9 
4 (0) 12 
5 10 (0) 
6 (0) 18 
(0) 14 21 
+4

答案將取決於語言,你沒有指定。 –

回答

-2

我認爲語言是Java作爲被指定的標籤。

我認爲解決方案將使用模數算術。

您想用(0)替換單元格位置(4 - 行號%4)中的值。在(行號%4)= 0的地方,(0)總是進入第二個單元格。因此,代碼爲:

public static void main(String[] args) { 
     int rows = 8; 
     int coulmns = 4; 
     int array; 
     for (int i = 1; i < rows; i++) { 
      for (int j = 1; j < coulmns; j++){ 
       if((j == (4 - (i % 4)) || (i % 4 == 0 && j == 2))) 
       { 
       System.out.print("0 "); 
       } 
       else 
       { 
       System.out.print(i*j+" "); 
       } 
      } 
      System.out.println(""); 
     } 
    } 

} 
+1

你應該發佈代碼而不是寫這個。 –

+0

夠公平的,這是我第一次回答,所以我想在編譯代碼時及時發佈一個總體想法! – GBishton

+0

@GBishton謝謝你的工作。請你簡單說明一下。 – KBM

-1

在第二個for循環試着這樣做:

for (int j = 1; j < coulmns; j++) { 
    int number = i*j; 

    if(i == 3 || i == 7) number = 0; 
    else if((j == 3 && i == 1) || (j == 3 && i == 5)) number = 0; 
    else if((j == 2 && i == 2) || (j == 2 && i == 6)) number = 0; 
    else System.out.print(number + " "); 
} 

您還可以,如果你想使用的模量。

0

我假設語言是Java,因爲它是指定的標記。

import java.util.*; 
import java.lang.*; 
import java.io.*; 

class StairCase 
{ 
    public static void main (String[] args) throws java.lang.Exception 
    { 
     int rows = 8; 
     int coulmns = 4; 
     int col=3; 
     int row=1; 
     int flag=0; 
     int array; 
     for (int i = 1; i < rows; i++) { 
      for (int j = 1; j < coulmns; j++) { 
       if(col==j && row==i){ 
        System.out.print("(0)"); 
        if(col>1 && col<4 && flag==0){ 
         col--; 
         if(col==1){ 
          flag=1; 
         } 
         row++; 
        }else{ 
         col++; 
         if(col==3){ 
          flag=0; 
         } 
         row++; 
        } 
       }else{ 
        System.out.print(i*j+" "); 
       } 
      } 
      System.out.println(""); 
     } 
    } 
} 

結果:

1 2(0)

2(0)6

(0)6 9

4(0)12

5 10(0)

6(0)18

(0)14 21

+0

你能給解釋請 – KBM

+0

首先你必須檢查一行只包含一個(0)。然後,如果它是該行的結尾,則減少名爲col的變量。否則,如果它等於第一列,則增加計數直到到達列的末尾,再次重複此操作,直到達到最後一行。 –