Adding integers to an int array
An array doesn't have an add method. You assign a value to an element of the array with num[i]=value;
.
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i=0; i < num.length; i++){
int neki = Integer.parseInt(args[i]);
num[i]=neki;
}
}
Arrays are different than ArrayList
s, on which you could call add
. You'll need an index first. Declare i
before the for
loop. Then you can use an array access expression to assign the element to the array.
num[i] = s;
i++;
An array has a fixed length. You cannot 'add' to it. You define at the start how long it will be.
int[] num = new int[5];
This creates an array of integers which has 5 'buckets'. Each bucket contains 1 integer. To begin with these will all be 0
.
num[0] = 1;
num[1] = 2;
The two lines above set the first and second values of the array to 1
and 2
. Now your array looks like this:
[1,2,0,0,0]
As you can see you set values in it, you don't add them to the end.
If you want to be able to create a list of numbers which you add to, you should use ArrayList.
To add an element to an array you need to use the format:
array[index] = element;
Where array
is the array you declared, index
is the position where the element will be stored, and element
is the item you want to store in the array.
In your code, you'd want to do something like this:
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++) {
int neki = Integer.parseInt(args[i]);
num[i] = neki;
}
The add()
method is available for Collections
like List
and Set
. You could use it if you were using an ArrayList
(see the documentation), for example:
List<Integer> num = new ArrayList<>();
for (String s : args) {
int neki = Integer.parseInt(s);
num.add(neki);
}