需要一些使用Java和矩阵的帮助

时间:2017-04-13 16:32:54

标签: java matrix

我正在学习并且有点麻烦。 我必须在图片上构建这样的矩阵 Matrix

但我不能在这些地方放星星。

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");
    }
}

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

2 个答案:

答案 0 :(得分: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  

答案 1 :(得分: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("");
    }
}