How to get a random letter in Java?
I want to get a random letter using something like
char ch = 'A' + randomNumber ; // randomNumber is int from 0 to 25
But that gives "loss of precision" compilation error (same if rando开发者_开发百科mNumber is only a byte). I guess with Unicode the above is a gross oversimplification.
This works but seems a bit clumsy:
char ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(randomNumber);
How should I do it ?
char ch = (char) (new Random().nextInt('Z' - 'A' + 1) + 'A')
You may replace 'A' and 'Z' by any character you want to achieve a wider range.
The problem is arising from trying to assign an int
into a char
.
Since an int
is 32-bits and char
is 16-bits, assigning an int
can potentially lead to a loss of precision, hence the error message is displayed at compile time.
If you know that you're going to be in the appropriate range, just cast:
char ch = (char) ('A' + randomNumber);
How about this? Ugly casting but no compilation errors. Should generate a random capital letter:
int rand = (int) (Math.random() * 100);
int i = 65 + (rand % 26);
char c = (char) i;
System.out.println(c);
精彩评论