2015-02-06 86 views
0
public int find(long searchKey) 
{ 

    int j; 
    for(j=0; j<nElems; j++) { // for each element, 
     if(a[j] == searchKey)  // found search value? 
      return j;    // then exit loop before end (exits entire function) 
    } 
    // reached end of for loop 
    return nElems;    // thus, can't find it 
} // end find() 
public void insert(long value) 
{ 
    a[nElems] = value; 
    nElems++; 
} 

我想实现此功能返回搜索键的索引,而不是搜索键的值。这里要说的是我不能让显示索引数组索引HighArray和HighArrayApp?

int searchKey = 33; // search for item 
    int indexToDisplay = j 
    if(arr.find(searchKey)) 
     System.out.println("Found " + searchKey + " at index: " + j); 
    else 
     System.out.println("-1"); 
+0

你为什么说'如果(arr.find(searchKey))'?对于任何非零值都是如此,除非我们正在查看两种不同的方法。另外,你说你不能让它显示索引;它代表什么?错误的索引? -1? – Dannnno 2015-02-06 18:32:18

+0

现在的输出是什么? – phil652 2015-02-06 18:32:35

回答

0
int searchKey = 33; // search for item 
int indexToDisplay = j 
if(arr.find(searchKey)) 
    System.out.println("Found " + searchKey + " at index: " + j); 
else 
    System.out.println("-1"); 

你设置indexToDisplay等于无主类真的,你想要做的是它设置为您找到的返回值()方法,所以像这样的:

int indexToDisplay = arr.find(searchKey); 

然后因为你的查找方法不返回一个布尔值,你可以做一个检查,看它是否是你的数组中的有效指标是这样的:

if(indexToDisplay != -1) 
    System.out.println("Found " + searchKey + " at index: " + j); 

我不太确定nElems是什么,但是如果你在数组中找不到你要找的东西,我会建议返回-1。这么干脆,我们有这样的事情:

public int find(long searchKey) 
{ 
    int j; 
    for(j=0; j<nElems; j++) { // for each element, 
     if(a[j] == searchKey)  // found search value? 
      return j;    // then exit loop before end (exits entire function) 
    } 
    // reached end of for loop 
    return -1;    // thus, can't find it 
} // end find() 
public void insert(long value) 
{ 
    a[nElems] = value; 
    nElems++; 
} 

,我们这样称呼它:

int searchKey = 33; // search for item 
int indexToDisplay = arr.find(searchKey); 
if(indexToDisplay != -1) 
    System.out.println("Found " + searchKey + " at index: " + indexToDisplay); 
else 
    System.out.println("-1");