random 4-digit number generator
The problem of random 4-digit number generator
In this blog, we will understand how to create a code for a random 4-digit number generator ranging between 0 to 9999. The code we will write will be specific to java language only.
Solution
The first will create a number in the string format. For this code, we will use an inbuilt function called random to create a random number in java.
String.format("%04d", number);
The above code will create a string of length “0” to “0000”. Here %04 represents the number of digits we want in our code. The format function is responsible for converting the text into string type.
public static String getRandomNumberString() { // 6 digit random Number it can generate. // from 0 to 999999 Random rnd = new Random(); int number = rnd.nextInt(999999); // Here we can convert number sequence into 6 character. return String.format("%06d", number); }
One may carry out the following: Make a class for BinaryNumber and include a function Object() { [native code] } that generates a char[] of 6 characters, each of which is generated using a random number generator between 0 and 1. If you want to display it, override the toString() method so that it returns the digits char[] as a string. then create a method called toInt() that multiplies the current digit by 10 to the power of I to convert the string’s characters one at a time into an integer:
char[] digits = {‘1’ , ‘0’ , ‘1’ , ‘1’ , ‘0’ , ‘1’}; //random int result = 0; for( int i = 0; i < digits.length; i++) { result += Integer.parseInt(digits[i]) * Math.pow(10, i); } return result;
Also Read: What is IndexError and how to solve it?