首页 > 解决方案 > 你能帮我解决我关于方法的代码吗?

问题描述

我的作业需要一些帮助,所以基本上我们需要创建一个代码,在其中我们在一个数组中输入 10 个数字,然后搜索数组,如果我输入的数字在那里,大部分代码就完成了。我只需要方法循环来搜索输入的数字是否在数组中谢谢你的帮助!!!

public static void main(String[] args) {
    int n, x, flag = 0, i = 0;
    Scanner s = new Scanner(System.in);
    int a[] = new int[10];
    System.out.println("Enter all the values:");
    for(i = 0; i < 10; i++)
    {
    System.out.print("Value "+(i+1)+": ");
        a[i] = s.nextInt();

    }

    System.out.print("Enter the value you want to find: ");
    x = s.nextInt();

    for(i = 0; i < 10; i++)
    {
        if(a[i] == x)
        {
            flag = 1;
            break;
        }

        else
        {
            flag = 0;
        }

    }
    if(flag == 1)
    {
        System.out.println("The value "+x+" is found at index "+(i+1));
    }

    else
    {
        System.out.println("The value "+x+" is found at index "+(-1));
    }
}

标签: java

解决方案


public static void main(String[] args) {

        int n, x, flag = 0, i = 0;
        Scanner s = new Scanner(System.in);
        int a[] = new int[10];
        System.out.println("Enter all the values:");
        for(i = 0; i < 10; i++)
        {
            System.out.print("Value "+(i+1)+": ");
            a[i] = s.nextInt();

        }

        System.out.print("Enter the value you want to find: ");
        x = s.nextInt();

        i = find(a, 10, x);
        if(i != -1)
        {
            System.out.println("The value "+x+" is found at index "+(i+1));
        }

        else
        {
            System.out.println("The value "+x+" is found at index "+(-1));
        }
    }

    private static int find(int a[],int n, int x) {
            int i, flag = 0;
        for(i = 0; i < n; i++)
        {
            if(a[i] == x)
            {
                flag = 1;
                break;
            }

            else
            {
                flag = 0;
            }

        }
        if(flag == 1) {
            return i;
        } else {
            return -1;
        }
    }

推荐阅读