How do I generate a random character between two specific characters? For e.g; I want to generate either one of 'h' or 'v'.
Thanks
How do I generate a random character between two specific characters? For e.g; I want to generate either one of 'h' or 'v'.
Thanks
If you want to generate a character, as you say, either h or v, you can generate a random number using the Random class as shown here. If for instance the random number is greater than 0.5, then choose v, if otherwise, choose h.
On the other hand, if you have a range of letters, you can either generate an array with the characters you want and generate a random number which will be used as an index to choose the random letter, or else, you can generate random number between 65 (Aschii for A) and 90 (Aschii for Z). You can find more Aschii characters here
Random r = new Random();
char c = r.nextBoolean() ? 'v' : 'h';
N.B. construct your Random object once and re-use it; don't re-construct it every time you want a random number!
how about:
import java.util.Random;
....
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100);
char chosen = randomInt % 2 == 0 ? 'h' : 'v';
To generate a random character between two given characters you could do the following:
char genRandChar(char char1, char char2)
{
char retVal;
int val1= (int) char1; //cast char1 to its integer ASCII value
int val2= (int) char2; //cast char2 to its integer ASCII value
//assuming val1<val2
retVal=(char)(val1+(int)(Math.random()*((val2-val1)+1)); //generate a random number between val1 and val2 and cast it to a character
return retVal;
}