Search code examples
javarandomletter

Is there a possibility to write a random letter generator as short as in python?


So I want to shorten my code and I asked myself if there is any possibility that a Random Letter generator in Java is as short as in python. In python it's just one a one liner.

The following Code is my Code yet:

int random = (int) Math.random()*25;

String[] letters ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}; 

String letter = letters[random]; 

Solution

  • If "short" just means one line, then any of these would do:

    char letter = "abcdefghijklmnopqrstuvwxyz".charAt((int) (Math.random() * 26));
    
    char letter = (char) ThreadLocalRandom.current().nextInt('a', 'z'+1);
    
    char letter = (char) ('a' + Math.random() * 26);