gpt4 book ai didi

java - 为什么我收到 "bound must be positive"错误?

转载 作者:行者123 更新时间:2023-12-01 14:06:15 24 4
gpt4 key购买 nike

我正在尝试编写模拟拼字游戏的代码。我设计了一个应该模拟拼字游戏袋的类,我试图通过在选择随机瓷砖后在 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);

}
}

最佳答案

this.bag.size()是 0,你传递了一个无效的参数给 nextInt() .

这在 Javadoc 中有明确说明:

n the bound on the random number to be returned. Must be positive.


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);

}

关于java - 为什么我收到 "bound must be positive"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33065644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com