完成查找该数据在数组中的索引,并在控制台输出找到的索引值。


/*
 已知一个数组 arr = {19, 28, 37, 46, 50}; 键盘录入一个数据
。定义一个方法,\完成查找该数据在数组中的索引,并在控制台输出找到的索引值。
 */
import java.util.Scanner;
public class 查找该数的索引 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个索引");
        int j = sc.nextInt();
        int qqq = qqq(j);
        System.out.println(qqq);
    }
        public static int  qqq(int j) {
            int arr[] = {19, 28, 37, 46, 50};
            int c = 0 ;
            //int b = 0 ;
            for (int i = 0; i < arr.length; i++) {
                if (i == j) {
                   c = arr[i];
                    break;
                } else if (arr.length < j) {
                  c=-1;
                    break;
                }
            }
            return c;
         //   return b;
        }
    }
/*
    public static void main(String[] args) {
        //定义一个数组,用静态初始化完成数组元素的初始化
        int[] arr = {19, 28, 37, 46, 50};
        //键盘录入要查找的数据,用一个变量接收
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要查找的数据:");
        int number = sc.nextInt();
        //调用方法
        int index = getIndex(arr, number);
        //输出索引变量
        System.out.println("index: " + index);
    }
    //查找指定的数据在数组中的索引
    public static int getIndex(int[] arr, int number) {
        //定义一个索引变量,初始值为-1
        int index = -1;
        //遍历数组,获取到数组中的每一个元素
        for(int x=0; x<arr.length; x++) {
            //拿number和数组中的每一个元素进行比较
            //如果值相同,就把该值对应的索引赋值给索引变量,并结束循环
            if(arr[x] == number) {
                index = x;
                break;
            }
        }
        //返回索引
        return index;
    }
}
 */```


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值