|
-
August 31st, 2009, 10:35 PM
#1
Random lines from a text file?
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?
Code:
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!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|