2017-04-13 16 views
0

我正在学习,并有一点麻烦。 我必须在图片上构建像这样的矩阵 Matrix需要一些帮助使用Java与矩阵

但是我不能在那个地方放一个星星。

public static void main(String[] args) { 
    int[][] twoD = new int[5][5]; 
    int i, j, k = 1; 
    for (i = 0; i < 5; i++) 
    for (j = 0; j < 5; j++) { 
      twoD[i][j] = k; 
      k++; 
    } 
    for (i = 0; i < 5; i++) { 
    for (j = 0; j < 5; j++) 
    System.out.print(twoD[i][j] + " "); 
     System.out.print("\n"); 
    } 
} 

这里是我的代码,请帮忙找

+0

您可以使用下面这个问题的答案http://stackoverflow.com/questions/23976995/how-to-print-out-an-x-using-nested-loops到很多解决您的 –

回答

1

可以从previous question采取的答案,稍微修改它像这样

public static void printCross(int size, char display) 
{ 
    int count = 0; //add a counter 
    for (int row = 0; row < size; row++) { 
     for (int col = 0; col < size; col++) { 
      count++; //increment each index we come across 
      if (row == col || row + col == size - 1) { 
       //print out the X using teh given display character 
       System.out.print(String.format("%-3s", display)); 
      } else { 
       //print out the current count 
       System.out.print(String.format("%-3s", count)); 
      } 
     } 
     System.out.println(); 
    } 
} 

输出

X 2 3 4 X 
6 X 8 X 10 
11 12 X 14 15 
16 X 18 X 20 
X 22 23 24 X 
+0

谢谢, 我会尝试。 –

0

我找到了我认为最简单的方法。

public static void main(String args[]){ 
    String[][] Matrix = { {" *"," 2"," 3"," 4"," *"} , {" 6"," *"," 8"," *","10"} , {"11","12"," *","14","15"} , {"16"," *","18"," *","20"} , {" *","22","23","24"," *"}}; 
    for(int i=0; i< Matrix.length; i++){ 
     for(int j=0;j < Matrix.length; j++){ 
      System.out.print(Matrix[i][j]+" "); 
     } 
     System.out.println(""); 
    } 
}