zzuli1117题查找数组元素

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值