Reputation: 39
I have a method called getWord() and I don't know what to add to it to actually choose a word from a text file. My text file consists of 5 words. Its easy printing all words in document, but how can I print one word differently each time I run the program. My code is below.
private Scanner file;
private final List<String> words;
public TextFile(){
words = readFile();
}
public String getWord(){
return numOfWords;
}
private List<String> readFile() {
List<String> wordList = new ArrayList<String>();
try {
file = new Scanner(new File("words.txt"));
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
} catch (Exception e) {
System.out.println("IOEXCEPTION");
}
return wordList;
}
public static void main(String[] args) {
TextFile file = new TextFile();
}
Upvotes: 0
Views: 261
Reputation: 2082
If you already have a list of the words in the text file, it looks like your question boils down to how to choose a random number for the index of the word to print. There are two ways to do this in Java (as far as I know).
You can use a Random
object.
List<String> words; // assign stuff to words
Random r = new Random();
//yields random number in the range of 0 to words.size()-1 inclusive
int num = r.nextInt(words.size());
Or you can use Math.random()
. Math.random()
returns a double between 0 (inclusive) and 1 (exclusive).
List<String> words; // assign stuff to words
int index = (int)(Math.random() * words.size());
Upvotes: 1
Reputation: 7576
There's also the version where your file is 100GB, but you have a word iterator:
Iterator<String> iterator = ...;
long wordNumber = 0;
String word = null;
while (iterator.hasNext()) {
String nextWord = iterator.next();
if (Math.random() < 1.0 / ++wordNumber) {
word = nextWord;
}
}
Upvotes: 0