1

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]; 
President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
Pereki
  • 31
  • 5

3 Answers3

5

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);
Andreas
  • 154,647
  • 11
  • 152
  • 247
1

Use the ASCII table. 97 = 'a', so just add your random number to that and convert to char.

ASCII Table

public class MyClass {
    public static void main(String args[]) {
        char z = (char)(97 + Math.random()*26);
        System.out.println("z = " + z);
    }
}
Greg Graham
  • 473
  • 7
  • 18
0

This is the shortest version to create 100 Characters:

Character[] result = new Random().ints(100,'a','z'+1).mapToObj(ch -> (char)ch).toArray(Character[]::new);
Finomnis
  • 18,094
  • 1
  • 20
  • 27