【发布时间】:2013-11-23 07:55:21
【问题描述】:
我正在做一个任务,指示如下,
编写一个方法,当传入一个整数搜索值时,如果搜索值在数组中,整数数组将返回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
我遇到的问题取决于我重写它的几种方式。就像现在一样,我没有收到任何错误,但无论我是什么数字,返回的值总是错误的从 main 传递给方法。
非常感谢任何关于如何纠正此问题的建议。
【问题讨论】:
-
这是尝试在 IDE 中使用调试器的最佳时机。在编译器执行时逐行遍历代码,这是学习成为一名更好的程序员的绝妙方法。
-
这也是使用编辑器修复代码格式的最佳时机 ..(我根本不会费心阅读格式不一致的代码。编程就像艺术 - 我不喜欢油漆飞溅。)
-
searchValue方法中你的Scanner有什么用? -
感谢大家的投入! @ZouZou,最初我计划包含一个 print 语句来询问用户他们想在数组中搜索什么值,但最终只是传递了一个值。感谢您指出我应该删除它,因为它不再需要存在。