Java RandomString类 [英] Java RandomString Class

查看:133
本文介绍了Java RandomString类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

HangMan RandomString类

以下是指示:

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

Create a RandomString class and implement the following:


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

  1. Create a file named guess_phrases.txt that contains phrases to be guessed in your Hangman game. This file will have one guess phrase per line.

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

A constructor that receives the name of a file to get string values from. The constructor should read in the phrases from the file and store them for later use.

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

A method that returns a random string value from the file; this value shouldn't be repeated until all guess phrases in the file have been used.

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

Create a main method to test that next is working correctly by repeatedly calling next & printing the result – you should not have any repeats, and the phrases should not be in the same order as in the file.

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

I created a file called guess_phrases.txt with random phrases. When I run this I get an error, also it is not printed randomly, why is this? How can I fix this ?

这就是我在RandomString类中的含义

This is what I have in the RandomString Class

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

    }
}


推荐答案

由于这显然是一个家庭作业问题,我只会给你一个提示 - 你的代码会发生什么如果文件是空的(没有任何短语)?

Since this is obviously a homework question, I'll just give you a hint -- what happens in your code if the file is empty (doesn't have any phrases)?

这篇关于Java RandomString类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆