Cannot invoke add on the array type

后端 未结 2 739

I have been given some code to tinker with, which is a prisoners dilema game are initially the players were set with this piece of code into an array.

IPDPlayer[         


        
相关标签:
2条回答
  • 2021-01-21 14:06

    Why do you want to have an array right at the very beginning; Use a list and once the input is over, you can always convert it to an array .

    List<IPDPlayer> ipdPlayerLst = new ArrayList<IPDPlayer>();
    ipdPlayerLst .add(.....);
    

    later

    IPDPlayer[] currentPlayers = new IPDPlayer[ipdPlayerLst .size()];
    currentPlayers =ipdPlayerLst.toArray(currentPlayers ); 
    
    0 讨论(0)
  • 2021-01-21 14:11

    See JLS 10.2. Array Variables and JLS 10.6. Array Initializers

    The length of the array to be constructed is equal to the number of variable initializers immediately enclosed by the braces of the array initializer. Space is allocated for a new array of that length. If there is insufficient space to allocate the array, evaluation of the array initializer completes abruptly by throwing an OutOfMemoryError. Otherwise, a one-dimensional array is created of the specified length, and each component of the array is initialized to its default value (§4.12.5).

    You are initializing an array with size 0,and you are accessing array in wrong way, you have to give the size of array while declaring it like:

    IPDPlayer[] currentPlayers = new IPDPlayer[sizeOfArray]; 
    

    Better use ArrayList for Your job like:

    List<IPDPlayer> currentPlayers = new ArrayList<IPDPlayer>();
    Scanner sc1 = new Scanner(System.in);
    System.out.println(" How many Tit-for-Tat?");
    int in_value = sc1.nextInt();
    for(int x = 0; x < in_value; x++)
    {
        currentPlayers.add(new TFTPlayer());
    }
    

    And if you want to return array from List use below code:

    currentPlayers.toArray(new IPDPlayer[0]);
    
    0 讨论(0)
提交回复
热议问题