我正在尝试编译一个在数组中搜索某个元素的程序,int target
. 它需要是一种public static boolean
方法,但我所拥有的代码无法打印返回值。为什么是这样?我没有考虑所有情况吗?感谢您的任何输入,我确定它一定是我忽略的小东西。
代码:
public static void main(String[] args)
{
int[] array = {3, 6, 9, 12, 15, 19, 21, -1, -45, 0};
int target = 2;
}
public static boolean linearSearch(int[] array, int target)
{
boolean linearSearch = false;
for (int i = 0; i < array.length; i++){
if(array[i] == target){
linearSearch = true;
}
else{
linearSearch = false;
}
}
return linearSearch;
}
}
此外,除此之外,可以将其编码为以下内容吗?
public class ArrayUtilities
{
public static void main(String[] args)
{
int[] array = {3, 6, 9, 12, 15, 19, 21, -1, -45, 0};
int target = 2;
}
public static boolean linearSearch(int[] array, int target)
{
boolean linearSearch = false;
for (int i = 0; i < array.length; i++){
if(array[i] == target){
linearSearch = true;
}
return linearSearch;
}
}