CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 18
  1. #1
    Join Date
    Aug 2009
    Posts
    8

    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!

  2. #2
    Join Date
    Oct 2008
    Posts
    77

    Re: Random lines from a text file?


  3. #3
    Join Date
    Aug 2009
    Posts
    8

    Re: Random lines from a text file?

    That didn't really help... I've tried googling the problem, and if that had worked, would I have posted here looking for advice?

  4. #4
    Join Date
    Aug 2009
    Posts
    44

    Re: Random lines from a text file?

    Code:
    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/r...ce/random.html
    Last edited by socialite; September 1st, 2009 at 04:18 AM.

  5. #5
    Join Date
    Aug 2009
    Posts
    8

    Re: Random lines from a text file?

    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?

  6. #6
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Random lines from a text file?

    Quote Originally Posted by spicypepper89 View Post
    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
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  7. #7
    Join Date
    Aug 2009
    Posts
    44

    Talking Re: Random lines from a text file?

    Code:
    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.

  8. #8
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Random lines from a text file?

    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
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  9. #9
    Join Date
    Aug 2009
    Posts
    44

    Re: Random lines from a text file?

    but they are not wrapped

  10. #10
    Join Date
    May 2009
    Location
    Lincs, UK
    Posts
    298

    Re: Random lines from a text file?

    You are still calling reader.readLine() twice, inside the loop and in the while. Change the do/while to:
    Code:
    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.

  11. #11
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Random lines from a text file?

    Quote Originally Posted by socialite View Post
    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
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  12. #12
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Random lines from a text file?

    Quote Originally Posted by jcaccia View Post
    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:
    Code:
    lineIn = reader.readLine();
    while (lineIn !=null) {
    	System.out.println(lineIn);
    	lineHolder[i++] = 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.

    Programs must be written for people to read, and only incidentally for machines to execute...
    H. Abelson and G. Sussman
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  13. #13
    Join Date
    May 2009
    Location
    Lincs, UK
    Posts
    298

    Re: Random lines from a text file?

    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

  14. #14
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Random lines from a text file?

    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.
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  15. #15
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Random lines from a text file?

    Quote Originally Posted by jcaccia
    I just can't help it, probably a defect I acquired several years ago that I can't shake off
    Me too, although I wish it was only several years ago I'd acquired it. Unfortunately, for me it started nearly 20 years ago

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

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured