Java Program to generate captcha string content.
Objective
Write a Java program to generate a 6-character random CAPTCHA string.
Algorithm / Approach
- Create a
char[]of size 6. - Use a
whileloop that runs until 6 valid letters are generated. - Generate a random integer between 65 and 186 (representing ASCII ranges).
- Check if the number falls within the ASCII ranges for uppercase (65-90) or lowercase (97-122) letters.
- If valid, cast the integer to a
char, store it, and increment the counter. - Convert the char array to a String and print.
CaptchaGen.java
class CaptchaGen {
public static void main(String[] ar){
char[] ran_chars = new char[6];
int i=0;
while(i!=6){
int c=(int)(Math.random()*122)+65;
if((c>='A'&&c<='Z')||(c>='a'&&c<='z'))
{
ran_chars[i] = (char)c;
i++;
}
}
String captcha = new String(ran_chars);
System.out.print("CAPTCHA:"+captcha);
}
}
Expected Output
//execution 1 CAPTCHA : hVABAx //execution 2 CAPTCHA : SiqlRr //execution 3 CAPTCHA : quiLPw
Explanation of the Program
- CAPTCHAs are used to differentiate humans from automated bots.
- Because we only want letters (no random symbols), we must validate the generated random number against the ASCII table before accepting it as part of our CAPTCHA string.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)