您能为我提供有关方法的代码的帮助吗?

时间:2019-12-29 13:22:24

标签: java

我需要一些作业方面的帮助,因此基本上我们需要创建一个代码,在该代码中,我们在数组中输入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));
    }
}

2 个答案:

答案 0 :(得分:-1)

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;
        }
    }

答案 1 :(得分:-1)

public class Main {
    public static int findIndexOfNumber(int numberToSearch, int[] numbers) {
        for(int i=0; i<numbers.length; i++) {
            if(numbers[i]==numberToSearch) {
                return i;
            }
        }
        return -1;
    }

    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();
        flag = findIndexOfNumber(x, a);
        System.out.println("The value "+x+" is found at index "+flag);
    }
}

您也可以尝试