Print Specific Row in 2D Array

我的未来我决定 提交于 2020-01-03 04:40:10

问题


How would I get just the second row to print in this 4x4 array?

double [][] table = new double[4][4];

for(int i = 0; i < table.length; i++){
 for(int j = 0; j < table[i].length; j++)
  table[i][j] = (Math.random() * 10);
}

回答1:


Use this

for(int j = 0; j < table[1].length; j++)
   System.out.print(table[1][j]+" - ");



回答2:


Use this

// table[0] == 1st row
// table[1] == 2nd row
// etc..

for(int i = 0; i < table[1].length; i++) 
    System.out.println(table[1][i]); // Print each item of the 2nd row



回答3:


Depending on the usage, you may want to use a method to print a specific row. Something like this

public void printRow(int r){
    for(int i=0; i<table[r-1].length; i++){
        if(i>0){
            System.out.print(", ");
        }
        System.out.print(table[r-1][i]);
    }
}

In this example, you would call printRow(2); when you want to print the 2nd row.



来源:https://stackoverflow.com/questions/34354340/print-specific-row-in-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!