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.
Is this homework? If so please tag your question appropriately.
Here is a clue: letters and numbers are all characters, which you could store in an array.
use the random generator function to generate a number in the range [0,26) and add the value of (int)'a' to that, and cast the result back to a char
Generate a set of numbers between 0 - 61 (there are 61 letters for upper and lower, plus digits) and map each to one of [0-9a-zA-Z], then concatenate the whole thing together.
Some basic things you can use:
- an array of all 26 characters in the alphabet and,
- 1 or 2 instances of a random number generator.
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
Did you try to search? Read these questions (and their answers first):
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));
}
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;
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?
You could have a look at RandomStringUtils, or at least at its source code.