为什么下面的代码返回1作为输出,但是如果我使用void并且插入的System.out.println()会返回数组元素?

问题描述 投票:-1回答:2
package removeduplicates;
public class RemoveDuplicates {

    static int remove_duplicate(int arr[], int N) {
        for (int i=0;i<N;i++) {
            return arr[I];
        }
        return 1;
    }

    public static void main(String[] args) {
        int a[]={1,2,3,4,5};
        int size=a.length;
        System.out.println(remove_duplicate(a,size));
    }
}
java return void
2个回答
0
投票

我看到您进行了很好的尝试,但是您对方法的概念有些偏离。首先,当您告诉某个方法“返回”时,它将立即停止该方法,它将不会继续执行循环并返回到您调用它的位置。所以当你打电话

return arr[i];

它将立即停止该方法,仅返回索引i处的内容。如果要打印每个元素,则不应返回任何内容,这是如何执行此操作的示例:

static void printElements(int arr[])
{
    //arr.length make the for loop go up until the length of the array
    for(int i=0; i <arr.length; i++) {
        System.out.println(arr[i]);
    }
}
public static void main(String[] args) {
    int a[]={1,2,3,4,5};

    printElements(a);
}

如果您是Java新手,建议阅读this以了解有关循环的更多信息,然后在youtube上查找解释方法的视频。


0
投票

这是删除给出int数组的重复项的简单方法。

软件包已删除重复项;公共类RemoveDuplicates {

static Set removeDuplicate(int arr[]) {

    Set list = new HashSet();

    for (int i : arr) 
        list.add(i);

    return list;
}

public static void main(String[] args) {

    int a[]={1, 1, 2, 2, 3, 3, 4, 4, 5, 5};

    System.out.println(removeDuplicate(a)); //1, 2, 3, 4, 5
}

}

© www.soinside.com 2019 - 2024. All rights reserved.