是否有可能编写与python一样短的随机字母生成器?

时间:2019-06-08 21:26:06

标签: java random letter

所以我想缩短我的代码,我问自己,Java中的Random Letter生成器是否有可能像python一样短。在python中,它只是一个一对一的衬里。

以下代码仍是我的代码:

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]; 

3 个答案:

答案 0 :(得分:4)

如果“短”仅表示一行,那么这些都可以:

char letter = "abcdefghijklmnopqrstuvwxyz".charAt((int) (Math.random() * 26));

char letter = (char) ThreadLocalRandom.current().nextInt('a', 'z'+1);

char letter = (char) ('a' + Math.random() * 26);

答案 1 :(得分:1)

使用ASCII表。 97 ='a',因此只需在其中添加您的随机数并转换为char。

ASCII Table

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

答案 2 :(得分:0)

这是创建100个字符的最短版本:

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