0

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!

Edited by Ezzaral: Added code tags. Please use them to format any code that you post.

2
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by Sekhrian
0

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.

Edited by NormR1: n/a

0

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.

0

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?

Edited by NormR1: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.