Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return int array with values greater than threshold

I need to add values to an int[] that are greater than a specific threshold. It does not work for me, because it returns wrong values. For example: "Output for values above 78: [85, 93, 81, 79, 81, 93]", but I get [93, 93, 93, 93, 93, 93]. Why is that so? Thank you.

public int[] getValuesAboveThreshold(int threshold) {

        // Output for values above 78: [85, 93, 81, 79, 81, 93]

        int[] a = new int[] { 58, 78, 61, 72, 93, 81, 79, 78, 75, 81, 93 };

        int temp[] = new int[1];

        for (int d : a) {

            if (d > threshold) {

                System.out.println(d);

                temp = new int[temp.length + 1];

                for (int i = 0; i < temp.length; i++) {

                    temp[i] = d;

                }

            }

        }

        return temp;

    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can return ArrayList instead of int[]. Try this code example

public static ArrayList<Integer> getValuesAboveThreshold(int threshold) {

    // Output for values above 78: [85, 93, 81, 79, 81, 93]

    int[] a = new int[] { 58, 78, 61, 72, 93, 81, 79, 78, 75, 81, 93 };

    ArrayList<Integer> temp = new ArrayList<>();

    for (int d : a) {

        if (d > threshold) {

            temp.add(d);

        }

    }

    return temp;

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading