Hi hi

What would I add to this code in order for it to pick a random word from the txt file?

try{
        RandomAccessFile raf = new RandomAccessFile("Words.txt", "rw");
        guessme = "";
        while ((guessme = raf.readLine()) !=null){
        guessme.toUpperCase();
        }
    }

Help is much appreciated!

Recommended Answers

All 4 Replies

Does the code compile and execute?
If not, please copy and paste the error messages here.

How does your code choose a word?
The while loop will read to the end of the file.

Yes, it runs without errors.
It reads a line of the text file, although it only reads the first line.
I need it to read any line of the txt file.
I think a math.random would be used here, but I'm not to sure how to implement it with this code.

I need it to read any line of the txt file.

Are all the lines of the txt file the same length?
If they are different lengths, then you can not find the first character of a line to be able to read that line.
If all the lines are the same length, then The beginning character of a line is at: lineNbr * lengthOfLine

If the lines are different lengths, you will need to read all the preceding lines to get to the desired lines.

Why not read all the lines into an array and use a random number to pick an element of the array?

Alright, will give that a go.

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.