Java - 在随机数组中搜索元素

Java - Searching an element in a random array

我执行了以下代码:

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() 或其他东西的显式转换有关吗?

您被打印数组的循环误导了,它实际上并没有打印数组元素。

变化:

for(int i : arr)
    System.out.print(arr[i] + " ");

至:

for(int i : arr)
    System.out.print(i + " ");

您将看到实际的数组值。

当您使用增强的 for 循环遍历数组时,您是在遍历数组值而不是数组索引。