Reputation: 51
I'm writing a short program which be able to generate 5 digits code mixed with 0-9, a-z, A-Z.
This is my code:
import java.util.*;
public class FiveDigitsRandom
{
public static void main(String[] args)
{
new FiveDigitsRandom().use();
}
public void use()
{
char choice;
while((choice=readChar()) != 'x')
{
switch(choice)
{
case'n':
generateAll();
break;
}
}
}
public char readChar()
{
System.out.print("Please choose n/x: ");
Scanner scanner = new Scanner(System.in);
return scanner.nextLine().charAt(0);
}
public void generateAll()
{
String[]code = new String[5];
for(int i=0; i<code.length; i++)
{
int random = generate0_2();
switch(random)
{
case 0:
code[i] = generate0_9();
break;
case 1:
code[i] = generate_a_z();
break;
case 2:
code[i] = generate_A_Z();
break;
}
}
for(int j=0; j<code.length; j++)
{
System.out.print(code[j]);
}
System.out.println(" ");
}
public int generate0_2()
{
return (int)Math.random()*3;
}
public String generate0_9()
{
int a = (int)(Math.random() * 10);
String AA = Integer.toString(a);
return AA;
}
public String generate_a_z()
{
char a = (char)((int)'a'+ Math.random() * ((int)'z' - (int)'a' + 1));
String AA = Character.toString(a);
return AA;
}
public String generate_A_Z()
{
char a = (char)((int)'A'+ Math.random() * ((int)'Z' - (int)'A' + 1));
String AA = Character.toString(a);
return AA;
}
}
It suppose to generate a random code as 0AzhG, Hg78N. But now I can only have 5 digits code with random number 0-9. Please tell me where is wrong in my code?? Thank you!
Upvotes: 1
Views: 2446
Reputation: 198
Maybe it's easely to use RandomStringUtils
import org.apache.commons.lang3.RandomStringUtils;
class Main {
public static void main(String[] args) {
// Prints only A-Z, a-z, 0-9
System.out.println(RandomStringUtils.randomAlphabetic(5));
// Prints only A-Z, a-z
System.out.println(RandomStringUtils.randomAlphanumeric(5));
}
}
Upvotes: 0
Reputation: 533750
A problem you have is that your won't have an even distribution. i.e. individual digits are more likely than individual letters. One way to have an even distribution is you have an even function.
public static char randomChar() {
// random.nextInt(62) would be faster.
int n = (int) (Math.random() * 62);
if (n < 10) return (char) ('0' + n);
n -= 10;
if (n < 26) return (char) ('A' + n);
n -= 26;
return (char) ('a' + n);
}
public static String randomString(int length) {
char[] chars = new char[length];
for (int i = 0; i < length; i++)
char[i] = randomChar();
return new String(chars);
}
Upvotes: 1
Reputation: 119
Your generate0_2 method is wrong.
public int generate0_2()
{
return (int)Math.random()*3;
}
When you cast it to int, it works like ((int)Math.random)*3 which means, it provides 0 every time.
change it to
public int generate0_2()
{
return (int)(Math.random()*3);
}
Upvotes: 2