Generating a random character out of any two in Java

后端 未结 4 1749
太阳男子
太阳男子 2021-01-23 08:32

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

相关标签:
4条回答
  • 2021-01-23 08:58

    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

    0 讨论(0)
  • 2021-01-23 09:04
    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!

    0 讨论(0)
  • 2021-01-23 09:05

    how about:

    import java.util.Random;
    
    
    ....
    
    Random randomGenerator = new Random();
    int randomInt = randomGenerator.nextInt(100);
    char chosen = randomInt % 2 == 0 ? 'h' : 'v';
    
    0 讨论(0)
  • 2021-01-23 09:08

    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;
        }
    
    0 讨论(0)
提交回复
热议问题