在ArrayList中获取Random有java.lang.IllegalArgumentException错误:n必须为正数

时间:2012-09-29 14:15:07

标签: java arraylist

在我的ArrayList中,我从我的ArrayList中获取了装备方法的随机项。

每当我使用我的测试仪时,当我尝试随机调用大小时,终端窗口会打印java.lang.IllegalArgumentException: n must be positive

我尝试将totalElements的值更改为元素的整数大小,然后错误将是OutOfBoundsExeption

import java.util.*;
import java.util.Scanner;
import java.util.Random;
public class GameMaster {



    private int turn, totalElements;
    private boolean winner;
    private Avatar x1;
    private Avatar x2;
    private ArrayList<Item> inventory;

    public GameMaster(Avatar a1, Avatar a2)
    {

    x2 = a1;
    x1 = a2;
    turn = 1;
    winner = false;
    inventory = new ArrayList<Item>();
    totalElements = 0;

    }

    private void fillInventory()
    {

    inventory.add( new Item( "Zealot Blades", true, 8 ) );
    inventory.add( new Item( "BFG", true, 13 ) );
    inventory.add( new Item( "Synthetic Cloth", false, 7 ) );
    // more items 


    inventory.add( new Item( "Gauss Rifle", true, 9 ) );
    inventory.add( new Item( "Flight Unit", false, 6 ) );

    totalElements = inventory.size();


    }

    public String equip()
    {
    Avatar w;
    String a;
    if (turn%2==1)
            w=x2;
    else 
            w=x1;

    if (w.beltIsFull())
    {

            a = w.getName() + "'s belt is full. \n";
    }

    else
    {
            turn++;
            Random generator = new Random();  
            Item rand = inventory.get(generator.nextInt(totalElements));
            //terminal window in blueJ: java.lang.IllegalArgumentException: n must be positive              

            a = w.getName()+" is equiped with "+rand.getName()+".";



    }
    return a;

}

1 个答案:

答案 0 :(得分:1)

异常告诉您totalElements小于或等于零。而且我认为那是因为你没有初始化它。 (我可以看到fillInventory方法,但我看不到你的代码在哪里调用它......)