简体   繁体   中英

Java get 100 random words from dictionary.txt file

I have a text file rext.txt and I'm trying to get first 100 random words from each line of the text file and put them into String array, but it's not working. I figured how to separate files from text and put them into array, but I can't figure where to include 100 to get them sorted. Thank you!!!

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;

public class New2 
    {
     public static void main(String[] args) throws FileNotFoundException 
        {
         Scanner sc = new Scanner(new File("dictionary.txt"));
         while (sc.hasNext())   
             {
             String word = sc.next();
             sc.nextLine();   
             String[] wordArray = word.split(" "); 
             //System.out.println(Arrays.toString(wordArray));
             int idx = new Random().nextInt(wordArray.length);
             String random = (wordArray[idx]);
             System.out.println(random);


        }
}
}

First, get your 100 words from the file. Then randomize the array.

String[] words = new String[100];
int pos = 0;
Scanner sc = new Scanner(new File("dictionary.txt"));
while (sc.hasNextLine() && pos < words.length) {
    String line = sc.nextLine();
    String[] wordArray = line.split("\\s+"); // <-- one or more consecutive 
                         //  white space characters.
    for (String word : wordArray) {
        words[pos] = word;
        pos++;
        if (pos >= words.length) {
            break;
        }
    }
}

Then you can shuffle and display words like

Collections.shuffle(Arrays.asList(words));
System.out.println(Arrays.toString(words));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM