klm klm - 15 days ago 6
Java Question

Can you explain me why this doesnt work?

I want to move 'o' to the right (by one in loop). Next prints should be:

-o--------
--o-------
---o------


and so on.

Can you tell me what i am doing wrong?

main:

char[][] tab = {
{ 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-' }}


for(int i = 0; i<tab[0].length-1; i++){
swap(tab[0][i], tab[0][i+1]);
prnt(tab);
}





static void prnt(char a[][]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
static void swap(char a, char b){
char temp = a;
a = b;
b = temp;

}

Answer

You are not updating the array of characters in the swap method, so the array itself will stay the same.

Try replacing your swap method by:

static void swap(char[][] a, int index){
    char temp = a[0][index]; 
    a[0][index] = a[0][index+1];
    a[0][index+1] = temp;
} 

Where you replace the call to swap with: swap(tab, i);

It's called pass-by-reference, ensuring the values in the array actually get updated.

Comments