好吧,我试图用偶数索引来反转行,但不是扭动这样的东西:
“6 5 4 3 2 1”
它写的是:
“6 5 4 4 5 6:
如何解决这个问题?
P.S。代码
int[][] a = new int[6][6];
int k = 1;
for(int i = 0; i < 6 ; i++)
{
for(int j = 0; j < 6 ; j++)
{
a[i][j]=k;
k++;
}
}
for(int i = 0; i < 6 ; i++)
{
for(int j = 0; j < 6 ; j++)
{
if(i%2 == 0)
{
int temp = a[i][j];
a[i][j] = a[i][a.length - 1 -j];
a[i][a.length - 1 - j] = temp;
}
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
答案 0 :(得分:-1)
你的循环应该一直运行到每一行的中间......并交换元素
// define the array
int[][] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
// print it
System.out.println(Arrays.deepToString(a));
// loop all the rows
for (int i = 0; i < a.length; i++) {
// loop every element on the row until the middle
for (int j = 0; j < a[i].length / 2; j++) {
// swap those
int temp = a[i][j];
a[i][j] = a[i][a[i].length - j - 1];
a[i][a[i].length - j - 1] = temp;
}
}
// print it again
System.out.println(Arrays.deepToString(a));