-4

Well,i'm trying to reverse the rows with even indexes, but instead of writhing such a thing:

"6 5 4 3 2 1"

it is writing this:

"6 5 4 4 5 6:

how to fix this?

P.S. code below

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();
    }
  • 2
    If you really want to learn programming - run your code with a debuger. – TDG Sep 21 '17 at 15:44
  • Use methods, and good variable names, to split the problem in simpler parts: `for (int rowIndex = 0; rowIndex < array.length; rowIndex += 2) { int[] row : array[rowIndex]; reverseRowElements(row); }`. Now the reverseRowElements method only needs one loop, and you won't confuse row and column indices, and the code will be much simpler to understand. – JB Nizet Sep 21 '17 at 15:47
  • https://stackoverflow.com/questions/2137755/how-do-i-reverse-an-int-array-in-java – bkis Sep 21 '17 at 15:49

1 Answers1

-1

your loop should just run until the middle of every row... and swap the elements

// 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));
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97