I am able to generate Random Numbers with Random method. But I want to create random numbers that are displayed in a binary format. The numbers must be within a specific range.
Random numbers should be between 5 and 10 digits, inclusive.
E.g.: 011110, 0111100, 010110101.
Try the Following Code Snippet (Random number generation from This Stack Overflow question)
import java.util.Random;
public class Main {
private static Random random = new Random();
private static final int MAX = 1023;
private static final int MIN = 16;
public static void main(String[] args) {
Integer randInt = random.nextInt((MAX - MIN) + 1) + MIN;
System.out.println("random binary is: " + Integer.toBinaryString(randInt));
}
}
MIN of 16 enforces a minimum of 5 binary digits where:
10000 is equal to 16
MAX of 1023 enforces a max of 10 binary digits where:
111111111 equal to 1023
The Utility method Integer.toBinaryString(int) converts the Integer into a binary readable format (enforcing the only '1's and '0's condition)
private Set set = new LinkedHashSet();
private Random rand = new Random();
public String getNo(){
int range = getRandom(5, 10);
StringBuffer nu = new StringBuffer();
for(int i=0,length=range;i<length;i++){
nu.append(getRandom(0, 1));
}
String nuString = nu.toString();
if(set.contains(nuString)){
return getNo();
}
set.add(nuString);
return nuString;
}
public int getRandom(int min, int max) {
return rand.nextInt((max - min) + 1) + min;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With