Java 数组索引HighArray和HighArrayApp?
将indexToDisplay设置为nothing实际上,您要做的是将其设置为find方法的返回值,如下所示:Java 数组索引HighArray和HighArrayApp?,java,arrays,indexing,Java,Arrays,Indexing,将indexToDisplay设置为nothing实际上,您要做的是将其设置为find方法的返回值,如下所示: 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"); int
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");
int indexToDisplay = arr.find(searchKey);
if(indexToDisplay != -1)
System.out.println("Found " + searchKey + " at index: " + j );
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++;
}
然后,由于find方法不返回布尔值,您可以执行如下检查以查看它是否是数组中的有效索引:
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");
int indexToDisplay = arr.find(searchKey);
if(indexToDisplay != -1)
System.out.println("Found " + searchKey + " at index: " + j );
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++;
}
我不确定nElems是什么,但是如果你在你的数组中找不到你想要的东西,我建议返回-1。所以我们总共有这样的东西:
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");
int indexToDisplay = arr.find(searchKey);
if(indexToDisplay != -1)
System.out.println("Found " + searchKey + " at index: " + j );
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++;
}
你为什么说如果arr.findsearchKey?这对于任何非零值都是正确的,除非我们考虑两种不同的方法。另外,你说你不能让它显示索引;它显示的是什么?错误的索引-1?现在的输出是什么?