Java随机字符串类
可能重复:Java随机字符串类,java,Java,可能重复: 以下是说明: 创建一个RandomString类并实现以下操作: 创建一个名为guess_phrases.txt的文件,其中包含在刽子手游戏中要猜测的短语。此文件每行将有一个猜测短语 接收要从中获取字符串值的文件名的构造函数。构造器应该从文件中读入短语,并将它们存储起来以备将来使用 从文件中返回随机字符串值的方法;在使用文件中的所有猜测短语之前,不应重复此值 创建一个main方法,通过反复调用next并打印结果来测试next是否正常工作–您不应该有任何重复,并且短语的顺序不应该与文
以下是说明: 创建一个
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) {
}
}
公共类随机字符串{
随机=新随机();
ArrayList猜测短语=新建ArrayList();
扫描仪文件扫描;
公共随机字符串(字符串猜测短语)引发FileNotFoundException{
//创建要从文件中读取的扫描仪对象
fileScan=newscanner(新文件(“guess_phrases.txt”);
//将文件中的所有短语添加到ArrayList中
while(fileScan.hasNext()){
String line=guessPhrases.nextLine();//获取输入
System.out.println(行);//打印行
猜词组。添加(行);//将行添加到数组列表
}
}
公共字符串next(){
int i=random.nextInt(guessPhrases.size());
返回猜测短语。获取(i);
}
公共静态void main(字符串[]args){
}
}
因为这显然是一个家庭作业问题,我只给你一个提示——如果文件为空(没有任何短语),代码中会发生什么?线程“main”java.lang.IllegalArgumentException:n在java.util.Random.nextInt(未知源代码)在RandomString.next(RandomString.java:32)处必须为正在RandomString.main(RandomString.java:40)中,必须向random.nextInt(int)传递一个正值。System.out.println(行)的输出是多少;