当前位置: 代码迷 >> Java相关 >> 二维数组的输出有关问题
  详细解决方案

二维数组的输出有关问题

热度:52   发布时间:2016-04-22 21:02:34.0
二维数组的输出问题
假设有一个二维数组b[][] = { { 1, 2, 3, 4, 5 }, { 4, 19, 6, 7, 8 },{ 9, 10, 11, 12, 13 }, { 14, 15, 16, 17, 18 } };,要用函数输出4所在的位置b[0][3]、b[1][0];可是我总是输出其中的一个,也不知道为什么?我的代码如下:
class xp2 {
static int a(int b[][], int c, int w[], int e[]) {
int m;
int n;
for (m = 0; m < b.length; m++) {
for (n = 0; n < b[m].length; n++) {
if (b[m][n] == c) {
w[0] = m;
w[1] = n;
}
}
}
return -1;
}

public static void main(String[] args) {
int b[][] = { { 1, 2, 3, 4, 5 }, { 4, 19, 6, 7, 8 },
{ 9, 10, 11, 12, 13 }, { 14, 15, 16, 17, 18 } };
int c = 4;
int w[] = { 0, 0 };
int p1 = 0;
int e[] = { 0 };
a(b, c, w, e);
for (p1 = 0; p1 < b.length; p1++) {
a(b, c, w, e);
boolean f=true;
if (f) {
System.out
.println("Found" + c + "at index" + w[0] + "," + w[1]);
} else {
System.out.println("not found");
}

现在求哪位大神解答一下,太急了!!!!!






------解决方案--------------------
static int[] a(int b[][], int c, int w[], int e[]) {
int m;
int n;
int i[]={0,0};
int j;
for (m = 0; m < b.length; m++) {
for (n = 0; n < b[m].length; n++) {
if (b[m][n] == c) {
w[0] = m;
w[1] = n;
// return 
System.out
.println("Found:" + c + " at index" + w[0] + "," + w[1]);
}
}
}
return null;
}

int b[][] = { { 1, 2, 3, 4, 5 }, { 4, 19, 6, 7, 8 },
{ 9, 10, 11, 12, 13 }, { 14, 15, 16, 17, 18 } };
int c = 4;
int w[] = { 0, 0 };
int p1 = 0;
int e[] = { 0 };
a(b, c, w, e);
for (p1 = 0; p1 < b.length; p1++) {
// a(b, c, w, e);
boolean f=true;
if (f) {
// System.out
// .println("Found:" + c + " at index" + w[0] + "," + w[1]);
} else {
System.out.println("not found");
}
功能可以实现,不过可以优化,因为很多东西写死了,先看着吧
------解决方案--------------------
public static void main(String[] args) {
int b[][] = { { 1, 2, 3, 4, 5 }, { 4, 19, 6, 7, 8 },
{ 9, 10, 11, 12, 13 }, { 14, 15, 16, 17, 18 } };

int key = 4;

List<String> result = findTheNum(b, key, "b", ",");
if (result!=null && result.size()>0) {
for (String value : result) {
System.out.println( "FIND" + key + " AT " + value);
}
}else{
System.out.println("Not Found!");
}
}

public static List<String> findTheNum(int[][] data,int findValue,String key,String split){
List<String> result = new ArrayList<String>();

String location = "";

for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
if (data[i][j] == findValue) {
location = key + ":" + i + split + j; 
result.add(location);
}
}
}
return result;
}
  相关解决方案