我执行了以下代码:
import java.util.Scanner;
public class Linear_Search {
public static void main(String[] args) {
int arr[] = new int[20];
for(int i = 0; i < arr.length; i++) {
arr[i] = (int)(Math.random() * 10) + 1;
}
System.out.print("Array is: ");
for(int i : arr)
System.out.print(arr[i] + " ");
//int arr[]= {1,2,4,5,6,7,8,43,6,4,2,6,8,3};
System.out.println();
System.out.println("Enter the number you want to search");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
boolean found = false;
String indices = "";
for(int i = 0; i < arr.length; i++) {
if(num == arr[i]) {
found = true;
indices = indices + i + ", ";
}
}
if(found == false) {
System.out.println(num + " does not exist");
}
else {
System.out.println(num + " found at index: " + indices.substring(0, indices.length() - 2));
}
sc.close();
}
}
输出:
Array is: 3 3 1 2 8 1 2 2 3 1 3 3 7 1 7 3 1 3 8 3
Enter the number you want to search
2
2 found at index: 0, 1, 8 ,15
为什么这会将随机索引显示为答案。当我使用自定义数组(如代码中注释的数组)时,代码工作正常。它与Math.random()上的显式强制转换有关吗?
答案 0 :(得分:8)
通过循环打印数组会误导你,因为它并没有真正打印数组元素。
变化:
for(int i : arr)
System.out.print(arr[i] + " ");
为:
for(int i : arr)
System.out.print(i + " ");
并且您将看到实际的数组值。
当您使用增强的for循环迭代数组时,您将迭代不在数组索引上的数组值。