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

问题描述 投票:1回答:1

我执行了以下代码:

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

java arrays linear-search
1个回答
8
投票

您通过循环打印数组来误导,这不会真正打印数组元素。

更改:

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

至:

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

你会看到实际的数组值。

当您使用增强的for循环迭代数组时,您将迭代数组值而不是数组索引。

© www.soinside.com 2019 - 2024. All rights reserved.