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