Is there functionality to generate a random character in Java?

前端 未结 18 2098
难免孤独
难免孤独 2020-11-28 06:00

Does Java have any functionality to generate random characters or strings? Or must one simply pick a random integer and convert that integer\'s ascii code to a character?

18条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 06:21

    Here is the code to generate random alphanumeric code. First you have to declare a string of allowed characters what you want to include in random number.and also define max length of string

     SecureRandom secureRandom = new SecureRandom();
     String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
        StringBuilder generatedString= new StringBuilder();
        for (int i = 0; i < MAXIMUM_LENGTH; i++) {
            int randonSequence = secureRandom .nextInt(CHARACTERS.length());
            generatedString.append(CHARACTERS.charAt(randonSequence));
        }
    

    Use toString() method to get String from StringBuilder

提交回复
热议问题