2015-05-26 27 views
-4

我是Java的新手,這是我的第一篇文章。Java - 從文本文件打印隨機單詞

我想創建一個程序,它將在屏幕上打印用戶指定數量的單詞,這些單詞從包含多頁文本的外部記事本文件中隨機提取。語法並不重要,但每個單詞都應該選擇相同的可能性(一種控制單詞重複的方法也不錯,但不是必需的)。

目前,我有Scanner提示用戶輸入一個數字,存儲爲變量「數字」,確定要拉多少單詞。程序應該讀取文本文件(或將其內容加載到某種列表或數組中?)並選擇至少一個字符長度的隨機單詞。重複循環「數字」次數並顯示整個結果字符串。

我需要幫助的部分是1)告訴程序訪問文件; 2)確保文字是隨機挑選的。我怎麼做?

非常感謝您的關注!

/* 
* Program description: Pulls a user-defined number of random words from an 
* external text file and prints the resulting text string on screen. 
* JDK version 1.7.0_60 
*/ 

import java.util.Scanner; 

public class RandomTextGen { 

    public static void main(String[] args) { 

     Scanner keyboard = new Scanner (System.in); 
     System.out.print("Enter number of words to pull: "); 
     int number = keyboard.nextInt(); 

     // Load text file 

     // Create loop to pull number of words in random order 

     System.out.println(""); //Output results 


    } 

} 
+1

發佈你的代碼到目前爲止...... –

+0

這將幫助解決你的問題:http://stackoverflow.com/questions/12028205/randomly-選擇一個文本文件 – JonasCz

+0

對不起,這是一個空閒時間的個人項目......感謝迄今的幫助。正如我所說,我對Java非常陌生,所以我不太關注隨着http://stackoverflow.com/questions/136474/best-way-to-pick-a-random中的代碼所發生的一切-subset-from-a-collection。我不清楚如何將我的外部文本文件合併到該代碼中,或者是否讓我可以靈活地選擇每次要更改多少個單詞而不更改代碼。很抱歉,如果有人可以分解並解釋發生了什麼,那很好。 。 。謝謝。 –

回答

2

閱讀文件,並將其存儲到List

FileInputStream in = new FileInputStream("yourfile.txt"); 
BufferedReader br = new BufferedReader(new InputStreamReader(in)); 

String strLine; 
List<String> filearray = new ArrayList<String>(); 

while ((strLine = br.readLine()) != null) { 

    for (int j = 0; j < myarray.length; j++){ 
     // get the whole line and split into words 
     String[] s = br.readLine().split(" "); 
     // put each word in the list 
     for (String s : strings) 
      filearray.add(); 
    } 
} 
in.close(); 

獲取List.size()並選擇一個隨機數

int size = filearray.size(); 
Random rn = new Random(); 
int randomWord = rn.nextInt(size); 

,並打印

System.out.println("Random word is: " + filearray.get(randomWord)); 

注意:重複多次,只要你想...

+1

您忘了將「作業」標籤添加到您的帖子;-) – Marged