I have a method for my app to read a random line from a text file and return it. Im using the randTxt() to read and return a random line from the txt file. but it only shows the same line (1st line) everytime.
public String randTxt(){
// Read in the file into a list of strings
InputStreamReader inputStream = new InputStreamReader(getResources().openRawResource(R.raw.randomstuff));
//ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String theLine="";
int i;
try {
i = inputStream.read();
while (i != -1) {
i = inputStream.read();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LineNumberReader rdr = new LineNumberReader(inputStream);
int numLines = 30;
Random r = new Random();
rdr.setLineNumber(r.nextInt(numLines));
try {
theLine = rdr.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return theLine;
}
How can I fix it? and Can someone explain what's wrong in my code?
inputStream.read does not return a line number. it returns the byte that was read. this isn't how you would read line by line. to read line by line, you should use buffered reader's readLine method. its probably easier at that point to read it all into a local array and use that array to randomly get an entry, rather than using a line number reader.
Here's the framework for doing what you need using BufferedReader. In this case, you don't need to store the values in a temp array.
You have gotten an answer of how to fix your code, but no explanation of why our original code did not work.
LineNumberReader.setLineNumber(int) does not go to the actual line, it just changes what number you call the current line.
So, say you read two lines, getLineNumber() will now return 2 (it started at 0 and increased by 1 each time a newline was encountered). if you now setLineNumber(10), getLineNumber() will return 10. Reading yet another line (your third) will cause getLineNumber() to return 11.
This is described in the Java Doc.
I think Random() function returns a value between 0 and 1. hence, you may have to multiply it with 100 to get an integer value. May even consider a MOD "your upper limit" operation to guarentee that the index you finally get is between 0 and your upper limit
Use the index you calculated thus, in your setLineNumber() method.
Edit: As john said, we can get whole number using Random() object.