如何修复这个2-D阵列? [英] How do I fix this 2-D array?
问题描述
public int [] [] flipPhoto(int [] [] picture)
{
int flip [] [] = picture;
int k = 0;
for(int i = 0; i< picture.length; i ++)
{
for(int j = picture [i] .length -1; j> = 0; j--)
{
flip [i] [k] = picture [i] [j];
k ++;
}
k = 0;
}
返回翻转;
}
我的尝试:
我试过改变i和k变量,但是没有用。
这就是我要打印的内容:
[[200,100,200],[100,200,100],[100,250,150]]
打印出来的是:
[[200,100,200],[100,200,100],[100, 250,100]]
如此接近我不知道该怎么做。
public int[][] flipPhoto(int[][] picture)
{
int flip[][] = picture;
int k = 0;
for (int i = 0; i < picture.length; i++)
{
for (int j = picture[i].length -1 ; j >= 0; j--)
{
flip[i][k]=picture[i][j];
k++;
}
k = 0;
}
return flip;
}
What I have tried:
I have tried inter changing the i and k variables but that doesnt work.
This is what i want to print out:
[[200, 100, 200], [100, 200, 100], [100, 250, 150]]
This is what prints out:
[[200, 100, 200], [100, 200, 100], [100, 250, 100]]
so close i dont know what to do.
推荐答案
你真的意识到这段代码:
You do realize that this code:
int flip[][] = picture;
复制对原始数组的引用,而不是复制数组本身?
所以当你这样做时:
Copies a reference to teh original array, not copies the array itself?
So when you do this:
flip[i][k]=picture[i][j];
它修改了翻转和图片 - 图片[i] [k]中的元素也被覆盖。
试试这个:
It modifies flip and picture - the element at picture[i][k] is also overwritten.
Try this:
int[] ar = new int[3];
ar[0] = 0;
ar[1] = 1;
ar[2] = 2;
int[] ar2 = ar;
ar2[1] = 7;
System.out.print(ar[0]);
System.out.print(ar[1]);
System.out.print(ar[2]);
你会得到072,因为ar2是引用,而不是元素的副本。
And you will get "072" because ar2 is a copy of the reference, not a copy of the elements.
这篇关于如何修复这个2-D阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!