• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to use Random( )?

 
Travis Gn
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Travis Gn
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 102
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Loren Rosen
Ranch Hand
Posts: 156
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic