Alex Ma Alex Ma - 6 months ago 25
Java Question

JAVA - Generate 5 digits code using Math.random()

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!

Answer

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);
}