到目前为止,我为这个方法编写的代码是:
int rowCount = 0;
int columnCount = 0;
Pair p = new Pair(0, 0);
public Pair search2D(int[][] data, int element) {
if(data[rowCount].length==columnCount)
{
rowCount++;
columnCount=0;
}
if(data.length > rowCount)
{
if(data[rowCount][columnCount] == element)
{
p = new Pair(rowCount, columnCount);
}
else
{
columnCount++;
search2D(data, element);
}
}
return p;
}"Pair“是我写的一个类,因为Java只允许我返回一个数字,而我试图返回保存元素位置的索引。
在我的main方法中,我有
int[][] table = new int[][] { {3, 2, 8}, {3, 5, 6} };
System.out.println(r.search2D(table, 5));
System.out.println(r.search2D(table, 8));但是,这两个输出都是(1,1)。有人告诉我不要使用任何循环,有人能给我指出正确的方向或告诉我问题在哪里吗?
发布于 2016-03-22 02:37:43
在找到r.search2D(table, 5)之后,您不会重置rowcount和columncount的值。因此,对于r.search2D(table, 8),您得到的答案也是1,1。
要解决此问题,请将函数修改为:
public Pair search2D(int[][] data, int element, int rowcount, int columncount){}并以search2D(data,element,0,0);的身份调用
https://stackoverflow.com/questions/36138721
复制相似问题