iamnards
iamnards

Reputation: 217

How to load random line from text file in android?

I have this piece of code;

Scanner s = new Scanner(getResources().openRawResource(R.raw.game));

try {
    while (s.hasNextLine()) {

        System.out.println(s.nextLine());

    }
} finally {
    s.close();
} 

How can I make to load a random line from this piece of code?

Thanks.

Upvotes: 0

Views: 1171

Answers (3)

Nick
Nick

Reputation: 1852

You could load the lines into another data structure such as an ArrayList and then use Random to generate a random index number.

Here's some code to put it into an ArrayList:

Scanner s = new Scanner(getResources().openRawResource(R.raw.game));
ArrayList<String> list = new ArrayList<String>();

try {
    while (s.hasNextLine()) {
        list.add(s.nextLine());      
    }
} finally {
    s.close();
} 

This code will return a random line:

public static String randomLine(ArrayList list) {
    return list.get(new Random().nextInt(list.size()));
}

Upvotes: 2

jac1013
jac1013

Reputation: 408

lets supose that you did the collecting to the String array lines:

int randomLine = (int)(Math.random()*lines.length);

there you got your random line.

Edit: oh well, you could use just String[]

Upvotes: 1

Onur A.
Onur A.

Reputation: 3017

First load all of them from file into a String array then randomly pick one of them from that String array.

Upvotes: 1

Related Questions