2015-02-06 22 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");