/*
已知一个数组 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;
}
}
*/```