wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes how to use Random( )? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how to use Random( )?" Watch "how to use Random( )?" New topic
Author

how to use Random( )?

Travis Gn
Greenhorn

Joined: Sep 11, 2003
Posts: 19
I am trying to take an 8 bit string ie. 01010101, and apply "noise" using the random class. I am pretty new to Java, and am having trouble generating a random number. What exactally do I need to "import" is it java.lang.Object ? to use random? can random be used with a string to alter the 8 bits? any help is greatly appriciated!


I need more help!
Travis Gn
Greenhorn

Joined: Sep 11, 2003
Posts: 19
Also, is there a better way to work with binary in java? I am wondering if I should rather than use a string, set a variable for each bit?
David Crossett
Ranch Hand

Joined: Feb 05, 2003
Posts: 102
I don't know about the best way to work with binary, but I can help with the random number generation. Nothing needs to be imported to use random(), as it is already a part of the java.lang pack. Also, java..Object is automatically inherited by all classes, so I'm not sure you'd ever directly import it (someone can comment on that if they know for sure). To generate random numbers with java, you need to know what number you want to start with (we'll call this 'a') and the range of the numbers you'd like to generate from (we'll call this 'b'). Given this, our formula looks like this:

For example, 1 + Math.random() * 1000 will give you a random number between 1 and 1000. Remember that ranom() returns a double, so usually you will see this formula cast to an integer, for example

Hope this helps a little!


David Crossett
-nothing important to say, but learnin' plenty-
Loren Rosen
Ranch Hand

Joined: Feb 12, 2003
Posts: 156
You can do C-style bit-twidling in Java. The bitwise and, or, xor and not operators (&,|,^,~) are all supported, as are two shift operators (<< and >> ) . There's also an unsigned right operator (>>> ) which doesn't exist in C.
Another way would be to use a BitSet (java.util.BitSet), which is a better choice unless, say, it causes performance problems. BitSets should result in easier-to-understand code, compared to using the bitwise and shift operators.
[ November 10, 2003: Message edited by: Loren Rosen ]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: how to use Random( )?
 
Similar Threads
Unique 8-length chars algorithm
choosing the Classes
From Byte[] to Ascii text String
how to generate key from string
Random() combined with a loop = trouble?