【问题标题】:Getting a random word from a string array text file从字符串数组文本文件中获取随机单词
【发布时间】:2014-08-27 14:37:18
【问题描述】:
 package hangman;

 import java.util.Random;

 public class Dictionary {

     int NUMBER_OF_WORDS = 81452;
     public static String FILE_NAME = "dictionaryCleaned.txt";
     private String[] dictionary = new String[NUMBER_OF_WORDS];

     public string getRandomWord() {
          Random rand = new Random();

          return randWord;
     }

 }

我正在尝试从包含文本文件“dictionaryCleaned.txt”的数组中随机生成一个单词,以便我可以将随机单词返回给单独类中的主方法。我觉得数组可能有问题,因为它似乎没有将文本文件加载到空数组空间中。我需要从“字典”中返回一个单词,但它正在躲避我。

谢谢

【问题讨论】:

  • 是否有代码可以将文本文件的内容加载到数组中,或者等待它神奇地发生?
  • 首先检查“文件到字符串数组”主题。然后检查“Java Random”教程。然后编辑您的问题。然后请我们再次写 cmets 或答案。
  • 您尚未使用任何数据填充字典。 stackoverflow.com/questions/2788080/reading-a-text-file-in-java getRandomWord() 应该返回一个字符串而不是字符串。下面回答了随机的正确使用方法。

标签: java arrays class random


【解决方案1】:

假设你省略了文件读取部分,

我会将 Random() 作为实例变量保留在您的字典中。

 private final Random random = new Random();

还有:

 public String getRandomWord() {
      return dictionary[random.nextInt(dictionary.length)];
 }

【讨论】:

    【解决方案2】:

    从字典中返回一个随机单词很简单:

    public String getRandomWord() {
         final Random rand = new Random();
    
         return dictionary[rand.nextInt(dictionary.length)];
    }
    

    但您仍然需要编写代码以将文件加载到字典中。

    【讨论】:

      【解决方案3】:

      首先,您必须将您的单词加载到数组中。那么只有你可以从你的单词数组中得到一个随机单词。

      所以你的代码应该是这样的 包刽子手;

      import java.util.Random;
      
      public class Dictionary {
           int NUMBER_OF_WORDS = 81452;
           public static String FILE_NAME = "dictionaryCleaned.txt";
           private String[] dictionary = new String[NUMBER_OF_WORDS];
      
           public void loadWordList(String fileName){
                // write your logic to read the file and load them into the dictionary array
           }
      
           public String getRandomWord() {
                Random rand = new Random();
                return dictionary[rand.nextInt(NUMBER_OF_WORDS)];
           }
       }
      

      【讨论】:

        【解决方案4】:

        您的getRandomWord 方法应该是:

        public String getRandomWord() {
           Random rand = new Random();
           int index = rand.nextInt(dictionary.length);
           String randWord= dictionary[index];
        
           return randWord;
         }
        

        【讨论】:

        • 投了反对票的人,你介意解释一下,这对我和其他人都有帮助。
        【解决方案5】:

        考虑到您的 dictionary 引用具有从字典文件加载的所有数据,然后加载随机字符串,您可以使用

        String randomValue = dictionary[new Random().nextInt(dictionary.length)];

        【讨论】:

          猜你喜欢
          • 2017-08-30
          • 1970-01-01
          • 1970-01-01
          • 2017-10-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多