2016-01-03 45 views
0

我想繪製一個數組,但我不知道執行該操作的正確方法。 這是我的數組。如何從數組中繪製「圖塊」?

int[][] map= 
      { 
        {1,1,1,1,1}, 
        {0,0,1,0,0}, 
        {1,1,1,1,1}, 
        {0,0,1,0,0}, 
        {1,1,1,1,1} 

      }; 

我知道我錯過了很多,而我似乎無法找到可以理解爲初學者編碼任何答案。

+1

什麼是 「磚」? –

+1

你是什麼意思「畫一個數組?」你能舉個例子嗎? –

+0

你想以某種方式「打印」?用循環也許? – Jan

回答

0
int[][] map= 
      { 
        {1,1,1,1,1}, 
        {0,0,1,0,0}, 
        {1,1,1,1,1}, 
        {0,0,1,0,0}, 
        {1,1,1,1,1} 

      }; 

int rows = 5; 
int cols = 5; 
int i, j; 

for (i = 0; i < rows; i++) { 
    for (j = 0; j < cols; j++) { 
    System.out.print(map[i][j] + " "); 
    } 
System.out.println(""); 
} 
+1

您應該從地圖數組中獲取長度,而不是對行和列變量進行硬編碼。 – Snusmumrikken

+0

我建更多的APON的代碼,這是我最後使用'INT [] [] =地圖 \t \t { \t \t \t \t {1,1,1,1,1}, \t \t \t \t {0,0,1,0,0}, \t \t \t \t {1,1,1,1,1}, \t \t \t \t {0,0,1,0,0}, \t \t \t \t {1,1,1,1,1} \t \t \t \t \t \t \t \t \t}; \t int rows = 5; \t int cols = 5; \t int i,j; \t爲(I = 0; I <行;我++){ \t對於(j = 0;Ĵ

0

使用GridPane:

public static void printImage(idPicture, path){ 
     image = new Image(path); 
     this.idPicture = idPicture; //in your case 0 or 1 

     for(int i = 0; i < width; i++){ 
      for (int j = 0; j< height; j++){ 
       if(map[i][j] == idPicture){ //check the current id 
        imageViewMatrix[i][j] = new ImageView(image); //load the image in the matrix 
        imageViewMatrix[i][j].setPreserveRatio(true); 
        imageViewMatrix[i][j].setFitWidth(imageWidth); 
        pane.add(imageViewMatrix[i][j], i, j); //add image to the pane 
       } 
      } 
     } 
    } 

這是對我來說最簡單的方法。但是,您必須爲每個要打印的圖像重複此過程,設置ID和路徑。

0

如果您只是想在控制檯中打印它們,那麼您可以嘗試循環。不過你也可以使用Java 8的一些魔力。

public static void main(String[] args) { 
    System.out.println("Started"); 
    int[][] map= 
     { 
       {1,1,1,1,1}, 
       {0,0,1,0,0}, 
       {1,1,1,1,1}, 
       {0,0,1,0,0}, 
       {1,1,1,1,1} 

     }; 

    Arrays.asList(map).stream().forEach((a) -> System.out.println(Arrays.toString(a))); 

    System.out.println(""); 

    Arrays.asList(map).stream().forEach((a) -> { 
     String b = Arrays.toString(a); 
     System.out.println(b.substring(1, b.length() - 1)); 
    }); 

    System.out.println(""); 

    Arrays.asList(map).stream().forEach((a) -> { 
     String b = Arrays.toString(a); 
     System.out.println(b.substring(1, b.length() - 1).replaceAll(",", " ")); 
    }); 
} 

輸出

Started 
[1, 1, 1, 1, 1] 
[0, 0, 1, 0, 0] 
[1, 1, 1, 1, 1] 
[0, 0, 1, 0, 0] 
[1, 1, 1, 1, 1] 

1, 1, 1, 1, 1 
0, 0, 1, 0, 0 
1, 1, 1, 1, 1 
0, 0, 1, 0, 0 
1, 1, 1, 1, 1 

1 1 1 1 1 
0 0 1 0 0 
1 1 1 1 1 
0 0 1 0 0 
1 1 1 1 1