2014-08-27 80 views
-1
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”的数组中随机生成一个单词,以便我可以将随机单词返回到我的主要方法单独的课程。我觉得数组可能有问题,因为它看起来没有将文本文件加载到空数组空间中。我需要从“字典”中返回一个单词,但它正在逃避我。从字符串数组文本文件中获取一个随机单词

谢谢

+3

是否有代码,您可以将文本文件的内容加载到数组中,或者您等待它发生奇迹般的变化? – 2014-08-27 14:41:29

+1

首先检查“File to String Array”主题。然后检查“Java随机”教程。然后编辑你的问题。然后请我们再次写评论或答案。 – 2014-08-27 14:41:34

+0

您还没有使用任何数据填写词典。 http://stackoverflow.com/questions/2788080/reading-a-text-file-in-java getRandomWord()应该返回一个字符串不是字符串。下面回答使用随机的正确方法。 – Revive 2014-08-27 14:47:30

回答

2

假设你留出了文件读取部,

我会保留随机()的实例变量在解释这里。

private final Random random = new Random(); 

和:

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

返回从dictionnary一个随机单词很简单:

public String getRandomWord() { 
    final Random rand = new Random(); 

    return dictionary[rand.nextInt(dictionary.length)]; 
} 

但你仍然需要编写的代码加载您的文件在您dictionnary。

0

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

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

0

getRandomWord方法应该是:

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

    return randWord; 
} 
+0

投下了这个的人,你会介意解释吗,这会帮助我和其他人一样。 – Omoro 2014-08-27 14:54:47

0

首先你必须加载你的话到阵列。那么只有你可以从你的单词数组中获得一个随机单词。

所以你的代码应该像 包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 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)]; 
    } 
} 
相关问题