Java String I/O Question

Status
Not open for further replies.
I have a brief java question. Hopefully there is an easy answer but I doubt it. I have a text file containing a number of strings such as:

ABC 123 XYZ
DEF 456 XYZ
GHI 789 XYZ

I read in one of the lines as a string and use it. Is there a way to randomly select one of the strings? How would I do it? Is there a way to accomplish this using Math.Random?

Thanks
 
Originally posted by RGrizzzz:
I have a brief java question. Hopefully there is an easy answer but I doubt it. I have a text file containing a number of strings such as:

ABC 123 XYZ
DEF 456 XYZ
GHI 789 XYZ

I read in one of the lines as a string and use it. Is there a way to randomly select one of the strings? How would I do it? Is there a way to accomplish this using Math.Random?

You would need to read all of the lines in (you'd probably want to use a Vector or ArrayList to store them), and then use Math.Random to randomly choose one of the members of that Vector or ArrayList. There are other ways to do it, but this is probably the best one. It only takes a potentially huge amount of memory, instead of a potentially huge runtime.

floccinau
 

asdfjkl;

Well-known member
1,351
read in the text file with BufferedReader, use the readLine() sub to read it into a Vector

once its in the Vector, create a random number generator sub and seed it with the Vector.size() ... if your stumped to how to make a random number, use:

code:<HR>
Code:
 new Double((Math.random() * int_Limit)).intValue()

where int_Limit is your random limit.

everything else should be gravy
 

Citrus538

Ars Legatus Legionis
12,722
You *could* read the lines sequentially X amount of times. If you reach EOF while going through the X number of lines, go back to the first line and continue reading until you've read X lines. The last line read will be as random as in the other suggestions.

I would also find a way to store the total number of lines in the file and use that as the maximum number randomly generated.

Whichever way you choose depends on the classic memory vs speed tradeoff.
 

ssmith

Ars Scholae Palatinae
928
If there are few enough strings, read the lot into memory:
code:<HR>
Code:
ArrayList strings = new ArrayList( );
ClassLoader systemLoader = ClassLoader.getSystemClassLoader( );
InputStream stream = systemLoader.getResourceAsStream( "strings.txt" );
BufferedReader aReader = new BufferedReader( new InputStreamReader( stream ) );
String lineIn = null;
while( null != ( lineIn = aReader.readLine( ) ) )
{
    strings.add( lineIn );
}
aReader.close( );<P>
And don't bother with that Math.random shit, use the much simpler java.util.Random:

code:<HR>
Code:
Random generator = new Random( );
int size = strings.size( );
String randomString = ( String ) strings.get( generator.nextInt( size ) );
System.out.println( randomString );
 
Status
Not open for further replies.