数组查表法(根据键盘录入索引,查找对应星期)
public static String getWeek(int week){
String[] arr = {" ","一","二","三","四","五","六","日"};
return arr[week];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("对应星期的索引是:");
int num = sc.nextInt();
String date = getWeek(num);
System.out.print("今天是星期"+date);
}
}
数组元素查找(查找指定元素第一次在数组中出现的索引)
public static int getIndex(int[] arr,int num){
for (int i = 0; i < arr.length; i++) {
if (arr[i] == num) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1,2,4,6,3,8,2,0,6};
int index = getIndex(arr, 8);
System.out.println("元素第一次出现的索引是:"+index);
}