2015-05-26 28 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