bubble
bubble

Reputation: 21

Why does this method not continue to look up an index after it first appears?

Why does "getIndex" not continue to look up an index after it first appears?

The write method implements an index that finds the first occurrence of a specified element in an array.

public static void main(String[] args) {
        //定义数组
        int[] arr = {5,7,2,3,5};
        //键盘录入
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要查找的数字:");
        int num = sc.nextInt();

        int index = getIndex(arr,num);
        System.out.println(index);
    }

    public static int getIndex(int[] arr,int value) {
        for(int i=0; i<arr.length; i++) {
            if(arr[i] == value) {
                return i;
            }
        }
        return -1;
    }

I expect the output is 0 and 4, but the actual output is 0.

Upvotes: 2

Views: 77

Answers (3)

Sudhir Ojha
Sudhir Ojha

Reputation: 3305

The return type of your method is int that means it will return one value at a time. Please try following:

    public static void main(String[] args) {
        //定义数组
        int[] arr = {5,7,2,3,5};
        //键盘录入
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要查找的数字:");
        int num = sc.nextInt();
        getIndex(arr,num);
    }

    public static void getIndex(int[] arr,int value) {
        boolean isFound = false;
        for(int i=0; i<arr.length; i++) {
            if(arr[i] == value) {
                System.out.println(i);
                isFound = true;
            }
        }
        if( !isFound)
           System.out.println("Not found");
    }

Upvotes: 1

Wilson Sim
Wilson Sim

Reputation: 521

Your getIndex() function stops after you return a value. When you return from a function, it will not continue running the function anymore!

Upvotes: 1

Ahmed Nabil
Ahmed Nabil

Reputation: 19006

Your method signature return value is ONLY ONE int which represents the first index occurrence for the given value.

public static **int** getIndex(int[] arr,int value)

So if the array contains the given value multiple time, ONLY the first index will be returned.

Upvotes: 0

Related Questions