I am creating a Java program that reads two text files, selects 10 words at random from each file and stores them in an array of two string lists. I have created the following code so far, however this only reads the words, it doesn't store them. I also need to serialize the array of 2 lists in a binary file. How can this be done? Some help with this would be greatly appreciated!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class RandomWordGenerator {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(randomFromFile("file1.txt", 10));
System.out.println(randomFromFile("file2.txt", 10));
}
private static ArrayList<String> randomFromFile(String fileName, int count) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(fileName));
ArrayList<String> words = new ArrayList<>();
while (scanner.hasNext()) {
words.add(scanner.next());
}
return randomFromWords(words, count);
}
static private ArrayList<String> randomFromWords(ArrayList<String> words, int count) {
ArrayList<String> randomWords = new ArrayList<>();
for (int i = 0; i < count; ) {
int random = new Random().nextInt(words.size());
if (randomWords.add(words.get(random))) {
i++;
}
}
return randomWords;
}
}
Aucun commentaire:
Enregistrer un commentaire