Approach :
We have to create a function which will return array of type char. OTP is the function which i have created. Then we have to define variable which will have all the numbers which will be included in the otp. Declare a array of type char which will store the digits of otp. Create a for loop to get the digits of otp and store them in the array.
Code :
package com.StepTowardsCoding;
import java.util.Random;
public class otp {
static char[] OTP(int len) {
System.out.println("Your OTP is ");
String num = "0123456789";
Random rand = new Random();
char[] otp = new char[len];
for (int i = 0; i < len; i++) {
otp[i] = num.charAt(rand.nextInt(num.length()));
}
return otp;
}
public static void main(String[] args) {
int length = 4;
System.out.println(OTP(length));
}
}
Output :
Your OTP is
4296
Explanation (Working) :
Execution of the code starts from main method, length is declared as 4. This is the length of OTP, which will be generated. length is 4 so the output is 4 digit number '4296'.
Method OTP is called with the parameter length, OTP is generated in this method. for loop is created to generate the OTP. As the value of len is 4 so the for loop is executed 4 times, that generates random number 0-9 each time store it in otp in string type
otp[i] = num.charAt(rand.nextInt(num.length()));here rand.nextInt(num.length()) is responsible for generating random number and num.charAt get the number at that index from num which is in string type and stored in otp[]. The otp is returned and printed.
2 Comments
this great post i like so please share more post like this
ReplyDeleteنقل اثاث راس الخيمة
thnx for your support
DeleteAsk Your Queries in the comments