Tuesday, June 13, 2017

Here i am posting a very useful program of random number.
please take a look.

import java.util.Random;
import java.util.Scanner;

public class OTP {
public static void main(String[] args) {

// create object of random class to generate a random number
Random r = new Random();

// create object of scanner to get input from keyboard
Scanner sc = new Scanner(System.in);

System.out.println("##welcome to the OTP generation system##");
System.out.println("enter 1 to generate a 6 digit numeric OTP");
System.out.println("enter 2 to generate a 8 letters alpha-numeric OTP");
System.out.print("enter 3 to generate a 6 letters mixed alpha-numeric OTP");

// take value for choice from keyboard
int choice = sc.nextInt();

if (choice == 1) {
System.out.println("6 digits numeric OTP: ");
for (int i = 1; i <= 6; i++) {
int var = r.nextInt(10);
System.out.print(var);
}

} else if (choice == 2) {
System.out.println("alpha-numeric 8 chars OTP: ");

for (int i = 1; i <= 4; i++) {
/*
* nextint() method will give a random number in the range of 0
* to 25, we will add 65 in it to get a value in the range of 65
* to 90 (values of alphabets in upper case) then the result
* will be converted into ASCII char using a type cast and will-
* be shown
*/
int var = 65 + r.nextInt(26);
System.out.print((char) var);
}

for (int i = 1; i <= 4; i++) {
int var = r.nextInt(10);
System.out.print(var);
}

} else if (choice == 3) {

System.out.println("mixed alpha-numeric OTP: ");
for (int i = 1; i <= 6; i++) {
int var1 = r.nextInt(10);
/*
* nextint() method will give a random number in the range of 0
* to 25, we will add 65 in it to get a value in the range of 65
* to 90 (values of alphabets in upper case) then the result
* will be converted into ASCII char using a type cast and will-
* be shown
*/
int var2 = 65 + r.nextInt(26);
/*
* nextint() method will give a random number in the range of 0
* to 25, we will add 97 in it to get a value in the range of 97
* to 122 (values of alphabets in lower case) then the result
* will be converted into ASCII char using a type cast and will-
* be shown
*/
int var3 = 97 + r.nextInt(26);
if (i < 3) {
System.out.print(var1);
} else if (i == 3) {
System.out.print((char) var2);
} else if (i == 4) {
System.out.print(var1);
} else if (i == 5) {
System.out.print((char) var3);
} else {
System.out.print(var1);
}
}

} else {
System.out.println("invalid choice....");
}

}
}

2 comments:

  1. //Here's my approach of printing the random characters
    String alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int n =alpha.length();
    Random r= new Random();
    for(int i=1;i<=4;i++)
    System.out.print(alpha.charAt(r.nextInt(n)));

    ReplyDelete