查找数组中最小元素的索引(Java)

我正在尝试编写一个将整数数组作为参数并返回数组中最小元素的索引的代码块。此外,如果列表是空列表,该函数应返回 -1。

http://img4.mukewang.com/60dc1f9d0001dbb611230272.jpg

到目前为止,我有,


public static int indexOfSmallest(int[] array){

    int index = 0;

    int min = array[index];


    for (int i = 1; i < array.length; i++){

        if (array[i] <= min){

        min = array[i];

        index = i;

        }

    }

        return index;

}

但是,我收到此错误并且不确定我需要修复什么。

http://img1.mukewang.com/60dc1fab0001272a18230803.jpg

任何帮助将非常感激。谢谢你。


月关宝盒
浏览 286回答 3
3回答

不负相思意

该错误是不言自明的。您无法处理空输入数组的情况。public static int indexOfSmallest(int[] array){&nbsp; &nbsp; // add this&nbsp; &nbsp; if (array.length == 0)&nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; int index = 0;&nbsp; &nbsp; int min = array[index];&nbsp; &nbsp; for (int i = 1; i < array.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; if (array[i] <= min){&nbsp; &nbsp; &nbsp; &nbsp; min = array[i];&nbsp; &nbsp; &nbsp; &nbsp; index = i;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return index;}如果最小元素出现多次,并且您想返回其第一次出现的索引,请将您的条件更改为:if (array[i] < min)&nbsp;

白猪掌柜的

您收到 IndexOutOfBoundsException 是因为您试图从行中的空数组中检索值:int&nbsp;min&nbsp;=&nbsp;array[index];只需使用以下命令检查此行之前的数组是否为空:&nbsp;if(array.length&nbsp;<&nbsp;1)&nbsp;return&nbsp;-1;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java