get Random in ArrayList has error of java.lang.IllegalArgumentException: n must be positive

Posted by gabrielle fregil on Stack Overflow See other posts from Stack Overflow or by gabrielle fregil
Published on 2012-09-29T14:15:07Z Indexed on 2012/09/29 15:38 UTC
Read the original article Hit count: 262

Filed under:
|

In my ArrayList, i have get a random Item from my ArrayList for the equip method.

Whenever i use my tester, the terminal window prints java.lang.IllegalArgumentException: n must be positive when I try to call random for the size.

I tried to change the value of totalElements to the integer size of the elements, then the error would be an 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;

}

© Stack Overflow or respective owner

Related posts about java

Related posts about arraylist