64.md 1.9 KB
Newer Older
W
wizardforcel 已提交
1
# Java 程序:线性搜索
W
wizardforcel 已提交
2 3 4 5 6

> 原文: [https://beginnersbook.com/2014/04/java-program-for-linear-search-example/](https://beginnersbook.com/2014/04/java-program-for-linear-search-example/)

#### 示例程序:

W
wizardforcel 已提交
7
该程序使用[线性搜索算法](https://en.wikipedia.org/wiki/Linear_search),在用户输入的所有其他数字中找出数字。
W
wizardforcel 已提交
8 9 10 11 12

```java
/* Program: Linear Search Example
 * Written by: Chaitanya from beginnersbook.com
 * Input: Number of elements, element's values, value to be searched
W
wizardforcel 已提交
13
 * 输出:Position of the number input by user among other numbers*/
W
wizardforcel 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
import java.util.Scanner;
class LinearSearchExample
{
   public static void main(String args[])
   {
      int counter, num, item, array[];
      //To capture user input
      Scanner input = new Scanner(System.in);
      System.out.println("Enter number of elements:");
      num = input.nextInt(); 
      //Creating array to store the all the numbers
      array = new int[num]; 
      System.out.println("Enter " + num + " integers");
      //Loop to store each numbers in array
      for (counter = 0; counter < num; counter++)
        array[counter] = input.nextInt();

      System.out.println("Enter the search value:");
      item = input.nextInt();

      for (counter = 0; counter < num; counter++)
      {
         if (array[counter] == item) 
         {
           System.out.println(item+" is present at location "+(counter+1));
           /*Item is found so to stop the search and to come out of the 
            * loop use break statement.*/
           break;
         }
      }
      if (counter == num)
        System.out.println(item + " doesn't exist in array.");
   }
}
```

输出 1:

```java
Enter number of elements:
6
Enter 6 integers
22
33
45
1
3
99
Enter the search value:
45
45 is present at location 3
```

输出 2:

```java
Enter number of elements:
4
Enter 4 integers
11
22
4
5
Enter the search value:
99
99 doesn't exist in array.
```