简体   繁体   中英

Reading from a text file Randomly

I just began developing android apps and i suddenly found it difficult reading a word from a text file, randomly,when a button is clicked.i tried putting all the words from the text file into an array and told it to display the word until the next line( randomly), but it doesn't seem to work. I want to know how to read and display words from a text file one by one and Randomly, every time a button is clicked !!!

您应该尝试逐字分割文本并将其放入数组中。

Create one big string by reading the file to the end. Split the big string into an arraylist by using string.split and give the split method the correct split parameter (" " or ","). Take a random entry out of the arraylist, where the maximum allowed random is the size of the arralist.

Sample code for displaying a word from an array of words.

Functions of most lines are written in comment.

string words[]; // array for words.
   /* code for reading text from text file and place words in text into words[] */
int sizeOfArray = numberOfWordsInArray; /* the value is set in the code of words placing into array */

Random rnd = new Random(); // random number generator

int index = rnd.nextInt(sizeOfArray); // nextInt returns random integer number between 0 and (sizeOfArray-1).

printf("%s\n",words[index]); // select a word by random number and display it.

I guess you have one word per line. Use code below to read file and save it into list.

    ArrayList<String> list = new ArrayList<String>();
try {
    InputStream instream = openFileInput("yourfile.txt");
    if (instream) {
        BufferedReader buffreader = new BufferedReader(new InputStreamReader(instream));
        String line;
        while (( line = buffreader.readLine())) {
        list.add(line);
    }
}
instream.close();
} catch (java.io.FileNotFoundException e) {
} 

Place above code inside onCreate method. Now use import java.util.Random to randomly select your item from list. Place below code inside OnClickListener.

public Item anyItem() 
    {   private Random randomGenerator = new Random();
        int index = randomGenerator.nextInt(list.size());
        Item item = list.get(index);
        System.out.println("Your Selected item is " + item");
        return item;
    }

Now you can do anything with the item returned from above anyItem() method, hoped it helped you.

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