Click to See Complete Forum and Search --> : Random lines from a text file?


spicypepper89
August 31st, 2009, 10:35 PM
Hi! I am writing a program that acts as a question answer game, and I've got most of it set up, but I need help making it select a random line of the text file and printing it out. At the minute, I've got it to read the entire file in, but how do I make it randomly select a line and print that one line alone?


public void questions()
{
try
{
FileReader fileReader;
BufferedReader reader;
fileReader = new FileReader("frenchQuestions.txt");
reader = new BufferedReader(fileReader);

String lineIn = reader.readLine(); //This String will hold the data brought in fron the text file.
do
{

System.out.println(lineIn);
lineIn = reader.readLine();
}while(lineIn != null);

System.out.println("Closing File");
reader.close();//This step is not necessary but is advised
}
catch(Exception e)
{ System.out.println("Cannot read from file"); }
}


Above is the code I have so far. I guess that I could put the lines into an array and randomly select an element from the array and print it, but I have no idea how to implement this in code :( Thanks for any help given!

postmortem
September 1st, 2009, 12:03 AM
http://lmgtfy.com/?q=+java+random+class

spicypepper89
September 1st, 2009, 12:13 AM
That didn't really help... I've tried googling the problem, and if that had worked, would I have posted here looking for advice?

socialite
September 1st, 2009, 04:15 AM
public class fileCont {


public static void main(String[] args)
{
FileReader fileReader = null;
BufferedReader reader = null;
String[] lineHolder = null;
String lineIn = null;
try
{

fileReader = new FileReader("frenchQuestions.txt");
reader = new BufferedReader(fileReader);
lineHolder = new String[100];
int i = 0;
int c=0;
lineIn = reader.readLine(); //This String will hold the data brought in fron the text file.
do
{

System.out.println(lineIn);
lineIn = reader.readLine();
lineHolder[i] = lineIn;
i++;
}while((c = reader.readLine())!=-1);
}
catch(Exception e)
{ System.out.println("Cannot read from file"); }
finally{
while(lineIn != null);

System.out.println("Closing File");
reader.close();//This step is not necessary but is advised
fileReader.close();
}}}

This is how to store into an array im sort-off. I am rookie and have never been able to get over the incompatible types error (it runs anyway but you probably get bytes returned rather than a string), or find an answer for it. Also you should only close in a finally statement to avoid recurring code and errors. Thats why youre class declerations to null go in the main block and youre actual
lineIn = new FileReader;
go into the try statement. I hope this helped :).

p.s hope you know how to use random ;)
http://www.cs.geneseo.edu/~baldwin/reference/random.html

spicypepper89
September 1st, 2009, 04:55 AM
Thanks socialite, that's great help :) However, I'm getting an error on the while line -- while((c = reader.readLine()) !=-1); that says there are incompatible types - found java.lang.String but expected int.

Is there any way to fix this?

dlorde
September 1st, 2009, 06:44 AM
However, I'm getting an error on the while line -- while((c = reader.readLine()) !=-1); that says there are incompatible types - found java.lang.String but expected int.

Is there any way to fix this?
Read the API docs for BufferedReader - the readline() method returns a String (as the name suggests), not an int, and null at end of stream, not -1.

However, the readline method reads a line every time it is called, so it doesn't really make sense to call it both inside the loop and in the loop control expression.

I suggest you rewrite the loop so that the readline method is only called once per iteration.

It is better to have an approximate answer to the right question than an exact answer to the wrong one...
J. Tukey

socialite
September 1st, 2009, 09:15 AM
public class LineReader{
public static void main(String[] args) throws IOException
{
FileReader fileReader = null;
BufferedReader reader = null;
String[] lineHolder = null;
String lineIn = null;
try
{

fileReader = new FileReader("frenchQuestions.txt");
reader = new BufferedReader(fileReader);
lineHolder = new String[100];
int i = 0;
do
{
lineIn = reader.readLine(); //This String will hold the data brought in fron the text file.
System.out.println(lineIn);
lineHolder[i] = lineIn;
i++;
}while(reader.readLine()!=null);
}
catch(Exception e)
{ System.out.println("Cannot read from file"); }
finally{
if(lineIn != null){
System.out.println("Closing File");
reader.close(); //This step is not necessary but is advised
fileReader.close();
}
}
}
}

fully working now thatnks to my freind dlorde and of course spicy pepper.

dlorde
September 1st, 2009, 09:40 AM
Incidentally, when you close the BufferedReader, the wrapped FileReader is automatically closed, so you don't need to explicitly close it as well.

The best is the enemy of the good...
Voltaire

socialite
September 1st, 2009, 09:51 AM
but they are not wrapped

jcaccia
September 1st, 2009, 10:10 AM
You are still calling reader.readLine() twice, inside the loop and in the while. Change the do/while to:
while ((lineIn = reader.readLine()) !=null) {
System.out.println(lineIn);
lineHolder[i++] = lineIn;
}
Also notice that after reaching EOF lineIn will be null, so the condition lineIn != null in the if in the finally block is always false.

dlorde
September 1st, 2009, 01:35 PM
but they are not wrapped
What do you think reader = new BufferedReader(fileReader); does?

If the BufferedReader didn't wrap the FileReader, it wouldn't be much use...

They know enough who know how to learn...
J. Adams

dlorde
September 1st, 2009, 01:59 PM
You are still calling reader.readLine() twice, inside the loop and in the while. Change the do/while to:Alternatively, the more verbose but simpler 'read-ahead' version:
lineIn = reader.readLine();
while (lineIn !=null) {
System.out.println(lineIn);
lineHolder = lineIn;
lineIn = reader.readLine();
}Some prefer this idiom as it aids readability and splits a nested expression that has two functions into separate expressions with a single function following the 'Best Practice' principle that classes, methods, and expressions should have a single, clearly defined function or role. It's more a matter of principle or personal preference than a serious concern for this expresssion, as the nested version has been popular since the early days of C.

[I]Programs must be written for people to read, and only incidentally for machines to execute...
H. Abelson and G. Sussman

jcaccia
September 1st, 2009, 02:22 PM
Dlorde, I agree with you, your version is a bit more verbose but, because of that, easier to understand. My version is more compact, but having an assignment and a comparison in the same statement is far from best practice and can be confusing specially for beginners... I just can't help it, probably a deffect I acquired several years ago that I can't shake off :o

dlorde
September 1st, 2009, 04:39 PM
I think it is a hang-over from early 'C' days, where it might have been more memory efficient, and for some coders reading/writing complex expressions was a geeky badge of honour. These days, saving bytes isn't so crucial, and the pendulum has swung in favour of simplicity and readability. But as you say, old habits die hard, and luckily this particular one is common enough that most coders will know it on sight, so I see it as kind of nostalgic ;)

Programs for sale: Fast, Reliable, Cheap: choose two...
Anon.

keang
September 2nd, 2009, 08:14 AM
I just can't help it, probably a defect I acquired several years ago that I can't shake off :o
Me too, although I wish it was only several years ago I'd acquired it. Unfortunately, for me it started nearly 20 years ago :(


I think it is a hang-over from early 'C' days
Yep, that was where I was corrupted.

jcaccia
September 2nd, 2009, 09:11 AM
Unfortunately, for me it started nearly 20 years ago :(
By several years ago I meant 20+ years as well and it was from early 'C' days. :(

keang
September 2nd, 2009, 09:49 AM
By several years ago I meant 20+ years as well
Arr so you were just trying to pass yourself off as a youngster then ;)

dlorde
September 2nd, 2009, 05:32 PM
I'll get me dressing gown & slippers...

The problem is never how to get new, innovative thoughts into your mind, but how to get old ones out!
D. Hock