user1545666
user1545666

Reputation: 67

Display random word from list

I am a beginner and I am making a an android app. My goal is to have the app randomly return a specific word from a list of word when a button is pressed. How should I go about doing this? Also, I am using eclipse and do not have much experience at all.

Upvotes: 0

Views: 3753

Answers (1)

Swayam
Swayam

Reputation: 16354

Since you already mentioned in your question that you want to generate a word from a list of words, I assume that you already have the list prepared.

Use the following to generate a random number and then display the word corresponding to that index.

Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100); // maximum value 100; you can give this as the maximum index in your list of words

Note : do not use Math.random (it produces doubles, not integers)

import java.util.Random;

EDIT :

Assume that you have the list of words in a String array which contains 30 words.

String wordList[] = new String[30];
// enter the words in the wordList (if you have a String, use a Tokenizer to get the individual words and store them in wordList)
int randomInt = randomGenerator.nextInt(30);
String wordToDisplay = wordList[randomInt];

Then, you can display wordToDisplay in your TextView by using mTextView.setText(wordToDisplay);

Upvotes: 3

Related Questions