亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何打印特定列的值

如何打印特定列的值

慕哥9229398 2022-06-15 15:12:23
所以我試圖弄清楚如何從給定的數組中打印特定的列,并且我完全卡住了。我設法打印整個矩陣,但沒有設法在特定列上打印。這是給學校的public class ex_1 {    public static void main(String[] args) {        int[][] arr = {{-1, -1, 1, 2, 3, -1},                {-1, 4, 5, 1, -1, -1},                {-1, -1, 6, 5, 4, 3},                {-1, 2, 5, 3},                {1, 2, 1}};        getNumFromCol(arr, 1);    }    public static int getNumFromCol(int[][] mat, int col) {        int temp = 0;        for (int i = 0; i < mat.length; i++) {            for (int j = 0; j < mat[i].length; j++) {                if (mat[i][j] != -1) {                    temp = mat[col][j];                }            }            System.out.print(temp);        }        return temp;    }}422
查看完整描述

2 回答

?
一只萌萌小番薯

TA貢獻1795條經驗 獲得超7個贊

訪問二維數組matrix時,您需要給出行號和列號的matrix[i][j]位置。ij


因此,如果要打印某一列col,則需要col在矩陣中每一行的位置打印該項目。它看起來像這樣:


public static void printColumn(int[][] matrix, int col) {

    for (int[] row: matrix) {

        System.out.println(row[col]);

    }

}

筆記

如果您想要一個漂亮的列格式,您可以使用StringBuilder逐步構建輸出。例如,如果您希望列格式為[1, 2, 3, 4, 5],它將如下所示


public static void printColumn(int[][] matrix, int col) {

    StringBuilder sb = new StringBuilder();

    sb.append("[ ");


    for (int[] row: matrix) {

        sb.append(row[col]).append(' ');

    }


    sb.append(']');


    System.out.println(sb.toString());

}



查看完整回答
反對 回復 2022-06-15
?
慕碼人8056858

TA貢獻1803條經驗 獲得超6個贊

首先你不需要做嵌套循環。如果要迭代整個矩陣,則需要嵌套循環 - 一個用于 X,一個用于 Y,但由于您已經知道該列,因此一個循環就足夠了。


    for (int j = 0; j < mat[col].length; j++) {

        temp = mat[col][j];

        System.out.println(temp);

    }


查看完整回答
反對 回復 2022-06-15
  • 2 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號