Generate 6 characters: the first character is randomly generated from the alphabets with odd ordering in the alphabet list (A, C, E, …, Y) the second character is randomly generated from the alphabets with even ordering in the alphabet list (B, D, F, …, Z) the third character is randomly generated from alphabet list (A to Z) each of the three digits is random generated from 1 to 9.
10 Answers
In java you can do char arithmetics. So
'A' + RNG.nextInt(26); will return you a random letter between 'A' and 'Z', where RNG is an instance of java.util.Random.
To build the string efficiently. Use a StringBuilder
Comments
Not sure if this is homework (it looks like it is), so I'll try to point you in the right direction of a possible approach:
- Recall that a random integer can be any integer X between two other specified integers Y and Z.
- How can you go from a random number to a random CHARacter?
- How could you take a random number between 0 and 13, and turn that into an even number between 0 and 26? An odd number?
- How can you use these ideas/concepts to your advantage for answering this question?
Comments
using my library dollar is simple:
@Test public void generateRandomString() { String string = $('a', 'z').shuffle().slice(3).join() + // take 3 random letters $('0', '9').shuffle().slice(3).join(); // take 3 random digits assertThat(string.length(), is(6)); } 1 Comment
assert.I want to generate 6 random characters including 3 random letters followed by 3 random numbers but I can only generate only letters or numbers at one time.
char a = randomLetter(); char b = randomLetter(); char c = randomLetter(); int x = randomNumber(); int y = randomNumber(); int z = randomNumber(); String result = new String()+a+b+c+x+y+z; Comments
Try with xeger and brics automaton.
import nl.flotsam.xeger.Xeger; import dk.brics.automaton.Automaton; public class RandomizeString{ public String generateRandomString(){ String regex = "[ACEGIKMOQSUWY][BDFHJLNPRTVXZ][A-Z][0-9]{3}"; Xeger generator = new Xeger(regex); String result = generator.generate(); return result; } } to understand more, learn Regular Expression.
abc123, or it can also bea1b2c3?