Im trying to get my android application to read from a text file and randomly chose an entry and then display it, How do i go about doing this? I think i have to use the buffer reader or input stream commands, but i have no idea how to use these, i've tried googling but havent found much help.
As far as i know (and with some help) i have to read the text file, add it to a string? and use the following command to randomly pick an entry
Random.nextInt(String[].length-1).
How do i go about doing this? :\ im quite new to all this bufferreader stuff etc.
You are asking about 2 different operations here. Don't cloud up the problem by muddling them together. You want to know how to:
Randomly choose 1 string from a group of strings.
// Read in the file into a list of strings
BufferedReader reader = new BufferedReader(new FileReader("inputfile.txt"));
List<String> lines = new ArrayList<String>();
String line = reader.readLine();
while( line != null ) {
lines.add(line);
line = reader.readLine();
}
// Choose a random one from the list
Random r = new Random();
String randomString = lines.get(r.nextInt(lines.size()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With