Adding integers to an int array

前端 未结 7 848
我在风中等你
我在风中等你 2021-02-05 01:57

I am trying to add integers into an int array, but Eclipse says:

cannot invoke add(int) on the array type int[]

Which is completely

7条回答
  •  执念已碎
    2021-02-05 02:26

    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 num = new ArrayList<>();
    for (String s : args) {
        int neki = Integer.parseInt(s);
        num.add(neki);
    }
    

提交回复
热议问题