2017-05-25 30 views
0

我正在寫一個hang子手程序,我想把word文本文件工作正常,能夠填充數組列表並從數組列表中生成一個隨機單詞。但我想做一些新的事情。程序在做什麼是相當簡單直接的,它是逐行讀取一個文本文件,每次讀取一行時它就會增加計數。但我想使用計數值作爲文本文件中某個單詞的索引從該文本文件生成一個隨機單詞。任何人都可以請幫我一下,我可以在哪裏獲得關於這個問題的文檔?使用count作爲字符串的索引如何生成隨機單詞?

public class WordReader { 


    private static String fileName = "Wordlist.txt"; 
    int count = 0; 

    public WordReader() throws FileNotFoundException { 
     File file = new File(fileName); 
     try(Scanner sc = new Scanner(new FileInputStream(file))){ 
      int count=0; 
      while(sc.hasNext()){ 
       sc.next(); 
       count++; 
      } 

     } 
    } 
} 
+0

爲什麼你想從內部獲得的隨機位置文本文件?這樣,每當你想要一個新的單詞,你必須打開並遍歷文件。將它加載到結構中並在需要時獲得單詞效率更高。 – Shane

回答

1
String[] words = new string[<Size of array, for example lines count>] 

然後通過行「字」陣列

using (StreamReader a = new StreamReader("Words.txt")){ 
    words[i] = a.ReadLine(); 
} 

添加單詞行現在你需要得到一個隨機行

Random rnd = new Random(); 
int random = rnd.next(0,words.Count()-1) 
string output = words[random]; 
+0

感謝大家的意見。 @ Taha225它像一個魅力工作。 –

0

它們加載到一個字符串數組列表,所以第一次初始化數組列表

ArrayList<String> dict = new ArrayList()<>; 

然後你需要添加一行到數組列表(假設它是每行一個字)

dict.add(sc.next); 

,那麼你需要得到這個詞的長度的隨機數,一旦所有詞都被添加到列表

Random rand = new Random(); 
int choice = rand.nextInt(dict.size()); 
String wordChoice = dict.get(choice);