【发布时间】:2014-07-21 16:30:05
【问题描述】:
在我的 for 循环的底部获取战利品。这可能是一个简单的逻辑错误,但由于某种原因,“如果”条件从未满足。很抱歉问了一些基本的东西,但我搜索了又搜索,似乎找不到答案。谢谢你帮助一个菜鸟。
Scanner scan = new Scanner(System.in);
System.out.println("How large would you like the array to be? (number)");
int arraySize = scan.nextInt();
scan.nextLine();
String [] myArray = new String [arraySize];
int i = 0;
if (arraySize <= 0 ) {
System.out.println("Please enter a positive integer for the array size. Rerun program when ready.");
} else {
while (i < myArray.length) {
System.out.println("Please type a string to be entered in the array");
myArray[i] = scan.nextLine();
i++;
}
System.out.println("Array contents: " + Arrays.toString(myArray));
}
System.out.println("What element would you like would you like to find in the array by performing a linear search?");
String search = scan.nextLine();
for (int j = 0; j < myArray.length; j++) {
if (myArray[j] == search){
int location = j + 1;
System.out.println("The element, " + search + " was found in the array, in which the linear search looped " + location + " times to find it." );
j = myArray.length;
}
}
【问题讨论】:
-
我的猜测:字符串相等又来了。永远不要将字符串与
==进行比较。请始终改用equals(...)或equalsIgnoreCase(...)方法。 -
if (myArray[j] == search){使用 .equals() -
比较两个字符串时必须使用
.equals。如:if (myArray[j].equals(search)){
标签: java arrays for-loop linear-search