0

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.

iamnards
  • 217
  • 2
  • 7
  • 18
  • If the file is small, reading to a string array is the way to go. If it's big, you'll need a different approach. How big is the file? – Gene Aug 10 '13 at 00:12

3 Answers3

2

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()));
}
Nick
  • 1,854
  • 1
  • 13
  • 16
1

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

Onur A.
  • 3,007
  • 3
  • 22
  • 37
1

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[]

jac1013
  • 408
  • 3
  • 11