为什么我收到"必须是肯定的"错误?

Oma*_*r N 2 java random

我正在尝试编写模拟拼字游戏的代码.我设计了一个应该模拟拼字游戏包的类,我试图通过在选择随机磁贴后在main中打印tileID来测试它.每当我运行代码时,我不断收到以下错误:

Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive at java.util.Random.nextInt(Random.java:388) at hw3.RandomBag.randomPick(RandomBag.java:39) at hw3.RandomBag.main(RandomBag.java:59

有人能告诉我为什么我收到这个错误吗?

import java.util.*;

public class RandomBag<E> implements Iterable<E> {

    // instance varibles
    private List<E> bag; // arraylist as the container
    private Random rand; // random number generator

    // constructors
    public RandomBag() { 
        bag = new ArrayList<E>();
        rand = new Random();    
    }

    public RandomBag(int seed) { 
        bag = new ArrayList<E>();
        rand = new Random(seed);

    }

    // returns the size of the bag
    public int size() { return this.bag.size(); }  

    public boolean isEmpty() { // returns true/false if the bag is/is not empty
        if (this.bag.isEmpty())
            return true;
        else
            return false;
    }  

    // adds the parameter element in the bag
    public void add (E element) {this.bag.add(element);} 

    // randomly selects an element using the random number generator 'rand' and removes that element from the bag, and returns the element
    public E randomPick() {

        int index = rand.nextInt(this.bag.size());
        E tileID = bag.remove(index);
        return tileID;
    } 

    // obtains an iterator for the bag, and returns it
    public Iterator<E> iterator() {
        // traverse bag using an iterator
        Iterator it = bag.iterator();
        return it;
    }

      //**
      //** main() for testing RandomBag<E>
      //**
    public static void main(String[] args) {

        RandomBag bag = new RandomBag();   

        Object tileID = bag.randomPick(); 
        System.out.println(tileID);

    }
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 9

如果this.bag.size()为0,则表示您传递了无效参数nextInt().

这在Javadoc中有明确说明:

n要返回的随机数的界限.必须是积极的.

nextInt(n)返回0到n-1之间的数字.你期望什么nextInt(0)回来?

在你的主要方法中,你试图挑选一个空袋子的元素.它不能工作.你应该在打电话之前检查包的大小randomPick().并且randomPick()应该在行李空的时候抛出异常.

public static void main(String[] args) {

    RandomBag bag = new RandomBag();   

    Object tileID = null;
    if (bag.size() > 0)
        tileID = bag.randomPick(); 
    System.out.println(tileID);

}
Run Code Online (Sandbox Code Playgroud)