What i am trying to do is
...
int sum[];
...
for(int z.....){
...
sum[z] = some_random_value;
...
}
But it gives an error at line sum[z]=ran; that variable sum might not have been initialized.
I tried int sum[] = 0; instead of int sum[]; but even that gave an error.
(I am basically a C programmer)
An array of dynamic size isn't possible in Java - you have to either know the size before you declare it, or do resizing operations on the array (which can be painful).
Instead, use an ArrayList<Integer>, and if you need it as an array, you can convert it back.
List<Integer> sum = new ArrayList<>();
for(int i = 0; i < upperBound; i++) {
sum.add(i);
}
// necessary to convert back to Integer[]
Integer[] sumArray = sum.toArray(new Integer[0]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With