HangMan RandomString类

可能重复:
Java RandomString类

以下是方向:

创建一个RandomString类并实现以下内容:

  1. 创建一个名为guess_phrases.txt的文件,其中包含要在Hangman游戏中猜到的短语。 此文件每行将有一个猜测短语。

  2. 一个构造函数,它接收文件名以从中获取字符串值。 构造函数应该读取文件中的短语并存储它们以供以后使用。

  3. 一种从文件中返回随机字符串值的方法; 在使用文件中的所有猜测短语之前,不应重复此值。

通过重复调用next并打印结果来创建一个主要方法来测试下一个正常工作 – 您不应该重复,并且短语的顺序不应与文件中的顺序相同。

我用随机短语创建了一个名为guess_phrases.txt的文件。 当我运行这个时我得到一个错误,它也不是随机打印的,为什么会这样? 我怎样才能解决这个问题 ?

错误线程“main”中的exceptionjava.lang.IllegalArgumentException:n必须为正数

 at java.util.Random.nextInt(Unknown Source) at RandomString.next(RandomString.java:32) at RandomString.main(RandomString.java:40) 

这就是我在RandomString类中的含义

 public class RandomString { Random random = new Random(); ArrayList guessPhrases = new ArrayList(); Scanner fileScan; public RandomString(String guessPhrases) throws FileNotFoundException { // create a Scanner object to read from the file fileScan = new Scanner(new File("guess_phrases.txt")); // add all of the phrases from the file into the ArrayList while (fileScan.hasNext()) { String line = guessPhrases.nextLine(); // get input System.out.println(line); // print line guessPhrases.add(line); // add line to array list } } public String next() { int i = random.nextInt(guessPhrases.size()); return guessPhrases.get(i); } public static void main(String[] args) { } } 

来自随机API

你可以看到,如果你将一个negetive数字或零传递给nextInt(pos),它将抛出一个IllegalArgumentException

int i = random.nextInt(guessPhrases.size());

绝对是guessPhrases.size()绝对是 ,因此是exception