How can i print just a single column from a two di

2020-05-09 22:24发布

问题:

I have this program im writing and i have to print just one column of a two dimensional array, not both.

for (int i = 0; i < sjf.length; i++)
{
    for(int j = 0; j < sjf[i].length; j++)
    {
        System.out.printf("%5d%4s   ", sjf[i][j], "|");
    }
    System.out.println();
}
System.out.println();

回答1:

For example you want to print the fifth column:

int column = 5;
for (int[] row : sjf) {
       System.out.printf("%5d%4s   ", row[column], "|");
}
System.out.println();


回答2:

Is it that what you need:

int j = <column_nr>;
for (int i = 0; i < sjf.length; i++)
        {
                System.out.printf("%5d%4s   ", sjf[i][j], "|");
            System.out.println();
        }
        System.out.println();


回答3:

Just don't use the inner for loop.

int colToPrint = 1;
for (int i = 0; i < sjf.length; i++)
{
    System.out.printf("%5d%4s   ", sjf[i][colToPrint], "|");
    System.out.println();
}

Here I've printed the second column i.e with index 1.



回答4:

Is this what you want? given the array sjf as an example int sjf[][]={{1, 3, 5}, {5, 7, 7}};

        for(int i = 0; i < sjf.length; i++){
            for(int j = 0; j < sjf[i].length; j++)
            {
                System.out.printf("%5d%4s   \n", sjf[i][j], "|");
            }
            //System.out.println();
        }
        System.out.println();

OUTPUT

1   |   
3   |   
5   |   
5   |   
7   |   
7   |   


回答5:

for (int i = 0; i < sjf.length; i++)
    {
        for(int j = 0; j < sjf[i].length; j++)
        {
            if(j==1)//in case second column is printed out
               System.out.printf("%5d%4s   ", sjf[i][j], "|");
        }
        System.out.println();
    }
    System.out.println();


回答6:

used an advanced for loop:

    // local variable to hold the column we wish to print       
    int colToPrint = 2;
    for (int row : sjf[colToPrint-1]) {
        System.out.printf("%5d%4s%n", row, "|");
    }   


标签: java arrays