Generating a random character out of any two in Java

后端 未结 4 1751
太阳男子
太阳男子 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 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!

提交回复
热议问题