Java School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a Java Expert!

Join 306,807 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,679 people online right now. Registration is fast and FREE... Join Now!




print a random line from a text file

 

print a random line from a text file

javarookie0

9 Apr, 2009 - 09:15 AM
Post #1

New D.I.C Head
*

Joined: 23 Jan, 2009
Posts: 18

Hi,

I do not understand how to print a random line from a text file. So far in my program i have been able to read the file but not to print out a random line

CODE


import java.util.Random;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class filereading {

    public static void main (String args []) {
    
        File file = new File("MyPhrases.txt");
        
        int count=0;
        try {
            
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                
                String line = scanner.nextLine();
           //   int intLine = Integer.parseInt(line);              
           //   Random random = new Random();
           //   String word = random.nextLine(line);
           //   System.out.println(line);
                count++;
           //   System.out.println(count);
          
            Random random = new Random();
        int rint = random.nextInt(count);
        System.out.println(count);
        
        }
            
        } catch (FileNotFoundException e) {
            
            System.out.println("error");
            
        }
      
    }
    
}



User is offlineProfile CardPM
+Quote Post


markhazlett9

RE: Print A Random Line From A Text File

9 Apr, 2009 - 09:46 AM
Post #2

Coding is a lifestyle
Group Icon

Joined: 12 Jul, 2008
Posts: 1,463



Thanked: 48 times
Dream Kudos: 25
My Contributions
Text files are meant to be read in sequential order. Unless you use a random access file there is not way to just read a random line. If you want to say read line 53 from a text file you can do this....

CODE
int counter =0;

while(file.hasNext())
{
if(counter == 53)
{
return something;
}
counter++;
}


Sorry for the formatting, don't have an IDE available. But that should do what you need. Cheers
User is offlineProfile CardPM
+Quote Post

javarookie0

RE: Print A Random Line From A Text File

9 Apr, 2009 - 10:08 AM
Post #3

New D.I.C Head
*

Joined: 23 Jan, 2009
Posts: 18

so how will i be able to print a random line when using Random access file? Could you show me this in code please?

This post has been edited by javarookie0: 9 Apr, 2009 - 10:09 AM
User is offlineProfile CardPM
+Quote Post

markhazlett9

RE: Print A Random Line From A Text File

9 Apr, 2009 - 10:17 AM
Post #4

Coding is a lifestyle
Group Icon

Joined: 12 Jul, 2008
Posts: 1,463



Thanked: 48 times
Dream Kudos: 25
My Contributions
That's a pretty complicated piece of code. What a random access file does is allow you to read items from a specific byte of code. So if you say go to byte 4* RECORD_SIZE it will proceed to that location and then you go per say, readInteger and it will read an integer. Here a link to the java tutorial on random access files. Try it out and if you're having any issues post your code on here and we'll help you out... Here's the link


http://java.sun.com/docs/books/tutorial/es...al/io/rafs.html
User is offlineProfile CardPM
+Quote Post

Fuzzyness

RE: Print A Random Line From A Text File

9 Apr, 2009 - 06:46 PM
Post #5

Comp Sci Student
Group Icon

Joined: 6 Mar, 2009
Posts: 1,183



Thanked: 181 times
Dream Kudos: 150
My Contributions
No i wouldnt do it that way.Open the file, and scan the line into a string. Make an arraylist of strings, and add the string to it. once its done. make a random that generates 0- max elements in the arraylist. then simply print what is at that element.Hope this helps!
User is offlineProfile CardPM
+Quote Post

javarookie0

RE: Print A Random Line From A Text File

10 Apr, 2009 - 05:39 AM
Post #6

New D.I.C Head
*

Joined: 23 Jan, 2009
Posts: 18

Thats the way i wanted to do it, but i couldn't seem to get the hang of doing it. If you could show me this in like code in an example that would be really helpful.

Thanks for your help.
User is offlineProfile CardPM
+Quote Post

Fuzzyness

RE: Print A Random Line From A Text File

10 Apr, 2009 - 07:09 PM
Post #7

Comp Sci Student
Group Icon

Joined: 6 Mar, 2009
Posts: 1,183



Thanked: 181 times
Dream Kudos: 150
My Contributions
Hmmmmm..... I suppose smile.gif
CODE

ArrayList<String> sentences = new ArrayList<String>();
String temp;
int numLines;
JFileChooser chooser = new JFileChooser();
           File infile = null;
           FileReader reader = null;
           if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
           {
               infile = chooser.getSelectedFile();
               reader = new FileReader(infile);
           }
        Scanner input = new Scanner(infile);
        while (input.hasNextLine())
{temp = input.nextLine();
sentences.add(temp);
numLines++;}
Random r = new Random();
System.out.println(sentences.get(r.nextInt(sentences.size())));

Breakdown :

1. JFileChooser allows the user to select a file to read the sentences from

2. It assign the File the selected file and the reader is assign a file to read!

3. Scanner is then created using the FIle selected, and using the hasNextLine() method, we make a while loop to keep cycling through every line adding it into the arraylist, but increase numLines as we go through it.

4. We then create a random object. (You will have to import Random) ArrayList has a method get() that allows us to retrieve something at that element. In this case we are going to get the string, and print it. Hence why it is in a System.out.println call

Hope this helps!
Goodluck!
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/20/09 09:47PM

Live Java Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month