2017-06-20 116 views
-1

我想從兩個單獨的數組中使用兩個for循環打印出X和Y座標。每個點都減少或增加。網格空間是500x500。我應該基本上結束與輸出顯示星號的行或者向上或向下。數組正確填充,並且X和Y座標正確遞減或遞增。我無法得到它的工作....用兩個循環打印

填充板方法填充b1數組與點的x成員和b2數組與點的y成員。

populateBoard(b1,b2,point); 

    for (int i = 0; i < matrix.length; i++) { 
     for (int j = 0; j < matrix.length; j++) { 
      if(i == b2[i] && j == b1[j]) 
       System.out.print("*"); 
      else 
       System.out.print(" "); 
     } 
     System.out.println(); 
    } 

在上面的代碼中,我的邏輯錯誤是什麼?但是,當我使用它(它顯然只適用於一點)。

if(i == b2[0] && j == b1[0]) 
+0

你的populateBoard方法的第三個參數有什麼作用? – aydinugur

+1

什麼是輸入(方法參數)和預期輸出? – Pshemo

+0

你應該使用1個循環而不是2個? –

回答

0

在上面的代碼的邏輯是這樣的假設:你的雙循環的I/J次迭代你會遇到一個點,其X/Y值恰好是正好等於I/J, 。

工作溶液是如下

private static void populateBoard(int[] xs, int[] ys, int w, int h) 
{ 
    Set<Point> points = new HashSet<>(); 
    for(int i=0;i<xs.length;i++) 
    { 
     int x = xs[i]; 
     int y = ys[i]; 
     points.add(new Point(x,y)); 
    } 
    for(int i=0;i<h;i++) 
    { 
     for(int j=0;j<w;j++) 
     { 
      Point p = new Point(j,i); 
      if(points.contains(p)) 
       System.out.print("■"); 
      else 
       System.out.print("."); 
     } 
     System.out.print("\n"); 
    } 
} 

當運行對一個簡單的例子的代碼:

int[] xs = {1,4,1,4,1,2,3,4}; 
int[] ys = {1,1,3,3,4,4,4,4}; 

populateBoard(xs, ys, 6, 6); 

它產生以下的(正確的)輸出:

...... 
.■..■. 
...... 
.■..■. 
.■■■■. 
...... 
0

嘗試這個。

boolean[][] temp = new boolean[matrix.length][matrix.length]; 
for (int i = 0; i < b1.length; ++i) 
    temp[b2[i]][b1[i]] = true; 
for (int i = 0; i < matrix.length; i++) { 
    for (int j = 0; j < matrix.length; j++) 
     System.out.print(temp[i][j] ? "*" : " "); 
    System.out.println(); 
}