Is there functionality to generate a random character in Java?

前端 未结 18 2065
难免孤独
难免孤独 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:23

    In fact mentioned methods don't generate real random char. To generate real random char you should give it a random seed! in example time in millisecond. this code generate 10 random char and then Convert it to String:

    import java.util.Random;
    public class MyClass {
        public static void main() {
    
         String randomKey;
    
        char[] tempArray={0,0,0,0,0,0,0,0,0,0};  //ten characters
    
        long seed=System.currentTimeMillis();
        Random random=new Random(seed);
        for (int aux=0; aux<10;aux++){
    
            tempArray[aux]=(char) random.nextInt(255);
            System.out.println(tempArray[aux]);
        }
    
        randomKey=String.copyValueOf(tempArray);  
    
    
          System.out.println(randomKey);
        }
    }
    

提交回复
热议问题