简体   繁体   English

Java:查找数组中大于零的最小数

[英]Java: Finding the smallest greater than zero number in an array

Finding smallest number is easy.找到最小的数字很容易。 I am finding it difficult to find a smallest greater than zero number in an array.我发现很难在数组中找到大于零的最小数。

public static int findSmallestOld(int[] arr) {
    int smallest = arr[0];
    for(int i=1; i<arr.length; i++) {
        if(arr[i]<smallest) {
            smallest = arr[i];
        }
    }
    return smallest;
}

Few example inputs could be很少有示例输入可以是
{0, 0, 0, 3} output = 3 {0, 0, 0, 3} output = 3
{0, 1, 0, 4} output = 1 {0, 1, 0, 4} output = 1

public static int findSmallest(int[] arr) {
    int smallest = Integer.MAX_VALUE;
    for(int i=0; i<arr.length; i++) {
        if(arr[i] > 0 && arr[i]<smallest) {
            smallest = arr[i];
        }
    }
    return smallest;
}

At the end, if smallest == Integer.MAX_VALUE, then all the array is filled of zeros.最后,如果 minimum == Integer.MAX_VALUE,则所有数组都填充为零。

change this:改变这个:

if(arr[i]<smallest)

to

if(arr[i]<smallest && arr[i] > 0) 

otherwise it will be overwritten by any value, whether it is a positive int or not.否则它将被任何值覆盖,无论它是否为正整数。

public static void main(String[] args) { // write your code here public static void main(String[] args) { // 在这里写你的代码

    int[] numbers = {12,20,85,40,95,54,75,45,50,43,11,9,5,6};
    int temp = numbers[0];
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] <  temp) {
            temp = numbers[i] ;

        }

    }
    System.out.println(temp);
}
if(arr[i]<smallest && arr[i]>0) {
    smallest = arr[i];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM