Java数组之线性查找

import java.util.Scanner;

public class LinearSearch {
    public static void main(String[] args) {
        System.out.println("please input numbers count:");
        Scanner scan = new Scanner(System.in);
        int count = scan.nextInt();
        int[] numbers = new int[count];
        System.out.println("please input numbers:");
        for (int i = 0; i < numbers.length; i++) {

            numbers[i] = scan.nextInt();
        }

        System.out.println("please input you want to find number:");
        int target = scan.nextInt();

        boolean find = false;
        for (int i = 0; i < numbers.length; i++) {
            if(numbers[i] == target)
            {
                System.out.println("we find " + target + ", it is " + (i + 1) +" number.");
                find = true;
                break;
            }
        }

        if(!find){
            System.out.println("sorry ,we can not find "+ target);
        }

        scan.close();
    }
}

//    please input numbers count:
//    5
//    please input numbers:
//    5
//    6
//    7
//    9
//    10
//    please input you want to find number:
//    9
//    we find 9, it is 4 number.

//    please input numbers count:
//    5
//    please input numbers:
//    5
//    6
//    7
//    9
//    10
//    please input you want to find number:
//    11
//    sorry ,we can not find 11
posted @ 2023-05-17 06:07  无风听海  阅读(14)  评论(0编辑  收藏  举报