zzuli1117题查找数组元素
import java.util.Scanner;
/**
* 输入n个整数构成一个数组,在这个数组中查找x是否存在,如果存在,删除x,并输出删除元素后的数组。如果不存在,输出“Not Found”。
*
* 定义一个查找函数find(),在数组a中查找x,若找不到函数返回-1,若找到返回x的下标,函数原型如下:
*
* int find(int a[], int n, int x);
*
* 然后在main()中,先调用函数find(),若查找失败输出“Not Found";若查找成功,则调用上一题中定义的函数del()删除该元素,再调用上一题中的PrintArr()输出删除元素后的数组内容。
*/
public class 查找数组元素 {
static void del(int[] a, int n, int position) {
int[] stime = new int[n - 1];
for (int i = 0; i < n - 1; i++) {
if (i < position) {
stime[i] = a[i];
} else {
stime[i] = a[i + 1];
}
}
PrintArr(stime, n - 1);
}
static void PrintArr(int a[], int n) {
for (int i = 0; i < n; i++) {
System.out.printf("%4d", a[i]);
}
System.exit(0);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();//n个数
int[] A = new int[n];
for (int i = 0; i < n; i++) {
A[i] = in.nextInt();//输入数据
}
int x = in.nextInt();// need search
find(A, n, x);
}
static int find(int a[], int n, int x) {
int temp = 0;
for (int i = 0; i < n; i++) {
if (a[i] == x) {
del(a, n, i);
temp = 1;
}
} if(temp == 0){
System.out.println("Not Found");
}
return -1;
}
}