我正在尝试弄清楚如何创建一种方法来在数组中查找字符串并将该字符串及其索引一起打印出来。我认为方法签名是正确的,但我不知道如何在方法中返回字符串值。
String name = search(array,"Dog"); //the method implementation in main
System.out.println(name);
.
public static int search(String[] array, String key)
{
for (int i= 0; i< array.length; i++)
{
if ( array[i] == key )
return i;
}
return ("Name cannot be found in array);
}
最佳答案
您不能从声明返回 int
的方法返回 String
。指示失败的最常见方法是返回超出范围的值:
return -1;
或者抛出异常:
throw new NameNotFoundException("Name cannot be found in array");
此外,这一行将不起作用:
if ( array[i] == key )
字符串必须是compared with equals()
, not ==
. ==
运算符检查字符串是否是相同的对象,而不是它们的内容是否相同。
if (key == null && array[i] == null ||
key != null && key.equals(array[i]))
并确保您没有在空引用上调用 .equals()
。上面的代码检查了这种可能性。
关于java - 搜索数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13770902/