Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java随机字符串类_Java - Fatal编程技术网

Java随机字符串类

Java随机字符串类,java,Java,可能重复: 以下是说明: 创建一个RandomString类并实现以下操作: 创建一个名为guess_phrases.txt的文件,其中包含在刽子手游戏中要猜测的短语。此文件每行将有一个猜测短语 接收要从中获取字符串值的文件名的构造函数。构造器应该从文件中读入短语,并将它们存储起来以备将来使用 从文件中返回随机字符串值的方法;在使用文件中的所有猜测短语之前,不应重复此值 创建一个main方法,通过反复调用next并打印结果来测试next是否正常工作–您不应该有任何重复,并且短语的顺序不应该与文

可能重复:

以下是说明:

创建一个
RandomString
类并实现以下操作:

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

  • 接收要从中获取字符串值的文件名的构造函数。构造器应该从文件中读入短语,并将它们存储起来以备将来使用

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

  • 创建一个main方法,通过反复调用next并打印结果来测试next是否正常工作–您不应该有任何重复,并且短语的顺序不应该与文件中的顺序相同

    我创建了一个名为guess_phrases.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) {
    
        }
    }
    
    公共类随机字符串{
    随机=新随机();
    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(行)的输出是多少;