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());
Solution 1:
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 = newScanner(getResources().openRawResource(R.raw.game));
ArrayList<String> list = newArrayList<String>();
try {
while (s.hasNextLine()) {
list.add(s.nextLine());
}
} finally {
s.close();
}
This code will return a random line:
publicstaticStringrandomLine(ArrayList list) {
return list.get(newRandom().nextInt(list.size()));
}
Solution 2:
First load all of them from file into a String array then randomly pick one of them from that String array.
Solution 3:
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[]
Post a Comment for "How To Load Random Line From Text File In Android?"