Home > Enterprise >  Return int array with values greater than threshold
Return int array with values greater than threshold

Time:11-11

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;

    }

CodePudding user response:

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;

}

CodePudding user response:

Since you initialise the temp array, it defaults to the default value of int and when you loop it to add values, it adds 'd' to all indexes. Try ArrayList instead:

           int[] a = new int[] { 58, 78, 61, 72, 93, 81, 79, 78, 75, 81, 93 };
            ArrayList<Integer> temp = new ArrayList<Integer>();
            for (int d : a) {
                if (d > 73) {
                    System.out.println(d);             
                        temp.add(d);
                }
            }
            System.out.println(temp);
  • Related