可能的重复:
HangMan RandomString 类 https://stackoverflow.com/questions/13818297/hangman-randomstring-class
以下是方向:
创建一个RandomString
类并实现以下内容:
创建一个名为guess_phrases.txt 的文件,其中包含要在 Hangman 游戏中猜测的短语。该文件每行有一个猜测短语。
接收文件名以从中获取字符串值的构造函数。构造函数应该从文件中读取短语并存储它们以供以后使用。
从文件中返回随机字符串值的方法;在使用文件中的所有猜测短语之前,不应重复此值。
创建一个主要方法,通过重复调用 next 并打印结果来测试 next 是否正常工作 - 不应有任何重复,并且短语的顺序不应与文件中的顺序相同。
我创建了一个名为猜测短语.txt与随机短语。当我运行这个时,我得到一个错误,而且它也不是随机打印的,这是为什么?我怎样才能解决这个问题 ?
这就是我在 RandomString 类中的内容
public class RandomString {
Random random = new Random();
ArrayList<String> guessPhrases = new ArrayList<String>();
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) {
}
}
由于这显然是一个家庭作业问题,我只会给您一个提示 - 如果文件为空(没有任何短语),您的代码中会发生什么?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)