将整数添加到int数组 [英] Adding integers to an int array
问题描述
我正在尝试将整数添加到int数组中,但是Eclipse表示:
I am trying to add integers into an int array, but Eclipse says:
无法在数组类型int []上调用add(int)
cannot invoke add(int) on the array type int[]
这对我来说完全不合逻辑.我还尝试了 addElement()
和 addInt()
,但是它们也不起作用.
Which is completely illogical to me. I also tried addElement()
and addInt()
, however they don't work either.
public static void main(String[] args) {
int[] num = new int[args.length];
for (String s : args){
int neki = Integer.parseInt(s);
num.add(neki);
}
推荐答案
要将元素添加到数组,您需要使用以下格式:
To add an element to an array you need to use the format:
array[index] = element;
其中 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;
}
add()
方法可用于 Collections
,例如 List
和 Set
.如果您使用的是 ArrayList
,则可以使用它(请参见
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);
}
这篇关于将整数添加到int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!