I want to add a new Value to my already existing Array. I made a new Array with the length of the already existing one and added one more Place for the new Value.
public class Measurement {
private int[] data;
public Measurement() {
data = new int[0];
}
public static void addValue(int value) {
int [] a = new int [data.length + 1];
for(int i = 0; i < data.length; i++) {
a[i] = data[i];
a[i + 1] = value;
}
for(int i: a) {
System.out.println(i);
}
}
}
I tried it with an already initialized Array and it worked, but I don't know what it doesn't with my existing try.
int[] a = {1,3,4,5,6,9};
int value = 10;
int[] b = new int[a.length + 1];
for(int i = 0; i < a.length; i++) {
b[i] = a[i];
b[i + 1] = value;
}
for (int i : b) {
System.out.println(i);
}
addValueis a static method, anddatais an instance field.i < data.lengthwill be false immediately. meaninga[i + 1] = value;will also never run. But i don't see the logic in adding the extra element in the loop anyway. just doa[a.length-1] = value;after your loop to add the extra value.