In Java how do you randomly select a letter (a-z)?

后端 未结 9 1360
北海茫月
北海茫月 2021-01-04 03:50

If I want to randomly select a letter between a and z, I assume I have to use the Random class:

Random rand = new Random();

Bu

相关标签:
9条回答
  • 2021-01-04 04:14
    char randomLetter = (char) ('a' + Math.random() * ('z'-'a' + 1));
    
    0 讨论(0)
  • 2021-01-04 04:16

    Letters, or more exactly, characters, are numbers (from 0 to 255 in extended ascii, 0 to 127 in non-extended). For instance, in ASCII, 'A' (quote means character, as opposed to string) is 65. So 1 + 'A' would give you 66 - 'B'. So, you can take a random number from 0 to 26, add it to the character 'a', and here you are : random letter.

    You could also do it with a string, typing "abcdefghijklmnopqrstuvwxyz" and taking a random position in this chain, but Barker solution is more elegant.

    0 讨论(0)
  • 2021-01-04 04:18

    To randomly select a letter from (a- z) I would do the following:

    Random rand = new Random();
    ...
    char c = rand.nextInt(26) + 'a';
    

    Since Random.nextInt() generates a value from 0 to 25, you need only add an offset of 'a' to produce the lowercase letters.

    0 讨论(0)
  • 2021-01-04 04:18
    Random r = new Random();
    char symbel = (char)(r.nextInt(26) + 'a');
    if(symbel>='a' && symbel <= 'z') {
        System.out.println("Small Letter" + symbel);
    } else {
        System.out.println("Not a letter" + symbel);
    }
    
    0 讨论(0)
  • 2021-01-04 04:21

    use the ascii value of the letters to generate the random number.

    0 讨论(0)
  • 2021-01-04 04:23

    why assume to use Random instead of Math.random? You can even make the code shorter...

    public static char genChar(){
        return (char)(Math.random()*26 + 'a');
    }
    
    0 讨论(0)
提交回复
热议问题