簡體   English   中英

在將Java與矩陣結合使用時需要一些幫助

[英]Need some help using Java with 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");
    }
}

這是我的代碼,請幫忙查找

您可以從上一個問題中得到答案,並像這樣稍作修改

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  

我找到了最簡單的想法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM