I can't seem to get the correct output on my 2 dimensional array.
The answer should be 1 5 9 2 6 10 3 7 11 4 8 12
and I get 1 5 9 2 6 10 3 7 11
The int intar line has to be that way.
Would appreciate any help!
Here is my code:
public class Assign8
{
开发者_如何学编程 public static void main (String args[]){
int intar[][] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
for (int i=0; i<intar.length; i++)
for (int j=0; j<intar.length; j++)
System.out.print(" " + intar[j][i]);
}
}
intar.length
will be the number of elements in intar- in this case, the number of arrays, or the number of elements in the jth dimension. In the ith dimension, you need to iterate through intar[j].length, or the length of the jth array.
That's tough to do because you don't know what j is going to be at the time you're iterating through i. If you can assume that all of the "inner" arrays are the same length, you could do:
for (int i=0; i<intar[0].length; i++){
// rest the same
}
try
for (int i = 0; i < intar.length; i++)
for (int j = 0; j < intar[i].length; j++)
System.out.print(" " + intar[i][j]);
as an aside, it's better style to use the i index before the j (i does come before j)
That is because the length of the array is 3, you should change your code in this way
for(int i=0; i < intar.length; i++) {
for (int j=0; j < intar[i].length; j++)
System.out.print(" " + intar[i][j]); }
精彩评论