Issue
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
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;
}
Answered By - Dinuka Silva
Answer Checked By - Senaida (JavaFixing Volunteer)