gpt4 book ai didi

java - 方法中的数组

转载 作者:行者123 更新时间:2023-11-29 10:02:25 27 4
gpt4 key购买 nike

我正在按照以下指示进行作业,

编写一个方法,当传递一个整数搜索值时,如果搜索值在数组中,则整数数组将返回 true,否则返回 false。调用该方法并在 main 中打印结果。

这是我目前的情况,

public class ArrayLab {
public static void main(String[] args) {
int[] array = {15, -2, 18, -9, 90, 17, 981};
int index;
boolean isThere = searchValue(15, array);
System.out.println(isThere);

public static boolean searchValue(int search, int[] array) {
Scanner input = new Scanner(System.in);
boolean isThere = true;
for(int index = 0; index < array.length; index++) {
if (search == array[index])
isThere = true;
else
isThere = false; } // end for

return isThere;
} // end searchValue

} // end class

我遇到的问题因我尝试重写此代码的几种方式而异。就像现在一样,我没有收到任何错误,但无论我输入多少数字,返回的值始终为 false从 main 传递给方法。

如有任何关于如何解决此问题的建议,我们将不胜感激。

最佳答案

你需要在找到数字后中断。否则,您也会继续检查其他数字。因此,如果最后一个数字返回 false,您只会看到“false”

for(int index = 0; index < array.length; index++) {
if (search == array[index]) {
isThere = true;
break;
} else
isThere = false;
}
}

关于java - 方法中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20160007/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com