Home > Back-end >  how to use math.random() function to get a random letter from a-z [duplicate]
how to use math.random() function to get a random letter from a-z [duplicate]

Time:09-28

This is what I used to have but I need to be able to do it without the string characters. How would I go about doing that? Needs to use Math.random().

String alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";//alphabet to randomize characters
char powerLetter1 = alphabet.charAt((int)(Math.random()*26)); 
char powerLetter2 = alphabet.charAt((int)(Math.random()*26));

CodePudding user response:

You can try this:

String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //alphabet to randomize characters
int rnd = (int) (Math.random() * alphabet.length());
System.out.println(alphabet.charAt(rnd));

Or here's another possible solution, though it uses Random instead of Math.Random:

Random random = new Random();
char c = (char) (random.nextInt(26)   'a');

CodePudding user response:

Use ASCII characters : A=65, B=66, C=67...

  •  Tags:  
  • java
  • Related