数组中查找元素

数组中查找元素

public class FindOne {
    public static void main(String[] args) {
        int[] nums = {3,93,62,34,29};
        int target = 62;

        //遍历数组如果输入一个不存在的目标值,会返回一个0,这时会有歧义。所以用数组中没有的负数代替下标来表示未找到具体的值。
        int result = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 622){
                result = i;
                break;
            }

        }
        System.out.println(result);
    }
}

-1

Process finished with exit code 0

import java.util.Scanner;

public class FindOne {
    public static void main(String[] args) {
        int[] nums = {3,93,62,34,29};
        System.out.println("请输入号码:");
        Scanner scanner = new Scanner(System.in);
        int target = scanner.nextInt();

        //遍历数组如果输入一个不存在的目标值,会返回一个0,这时会有歧义。所以用数组中没有的负数代替下标来表示未找到具体的值。
        int result = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                result = i;
                break;
            }
        }
            if (result < 0 || result > nums.length-1){
                System.out.println("未找到该身份证记录");
            } else {
                System.out.println("该身份证为:"+nums[result]);//nums[中括号中的是数组具体值的位置编号],整体代表该数组中该位置具体的值。
            }


    }
}

请输入号码:
93
该身份证为:93

Process finished with exit code 0
posted @ 2022-05-02 23:17  追风的羊  阅读(227)  评论(0)    收藏  举报