DEV Community

kali kimanzi
kali kimanzi

Posted on

Finding a minimum number in a Java Array

Sometime back we were given a java assignment but I realized the concepts looked easy but some of my friends had problems implementing them that is why I have decided to be sharing some of the java assignments that I have done in the past to help students and learners who are new to programming in java.

Question:

Write a function int findMin (int[] numbers), which yields the smallest element of numbers that contains positive integers. The result shall be -1, if numbers has the value null or the array does exclusively contain positive integers. Use several test cases.

Java Source Code:



public class FindingMinimum {

    public static void main(String[] args) {
        // int[] numbers =null;
        // System.out.println(x);
        // int[] numbers= {2,3,4,5,6,20,1,-5};
        int[] numbers = { 2, 3, 4, 5, 6, 20, 1 };
        //int[] numbersSet1= {2,3,4,5,6,20,1,-5};

        int minimumNumber = findMin(numbers);
        System.out.println("The Minimum number is :\t"+minimumNumber);
        //minimumNumber = findMin(numbersSet1);
        //System.out.println("The Minimum number is :\t"+minimumNumber);

    }

    static int findMin(int[] numbers) {
        int minValue = numbers[0];

        if (isExclusivePositive(numbers)) {

            for (int i = 1; i < numbers.length; i++) {
                if (numbers[i] < minValue) {
                    minValue = numbers[i];
                }
            }
        } else {
            minValue = -1;
        }
        return minValue;

    }

    static boolean isExclusivePositive(int[] numbers) {
        int value = 0;

        for (int i = 0; i < numbers.length; i++) {
            value = numbers[i];

            if (value < 0)
                return false;
        }

        return true;
    }

}


Output:

The Minimum number is : 1

I hope you have liked this article.

I am Kali Kimanzi a Masters student at University of Applied Sciences Upper Austria, I am a software developer at NTUITY a brand of neoom group gmbh Wien | Freistadt. I take interest in Data sciences using python and i use python libraries like pandas, numpy and Matplotlib. I specialize in Python, PHP/Laravel, Java.

Social media links

Kali kimanzi @ Facebook: Kali Kimanzi
Kali Kimanzi @ Linkedin: Kali Kimanzi
Kali Kimanzi @ instagram : Kali Kimanzi
Kali Kimanzi GitHub: Kali Kimanzi
kali kimanzi Twitter : Kali Kimanzi

Top comments (0)