0

I have this piece of code that generates a random characters (ASCII)

public char getRandChar(){ return (char)rand.nextInt(27); }

and then I'll print it out using this

System.out.println(new Character(getRandChar()));

How but apparently it is returning a blank value

KyelJmD
  • 4,682
  • 9
  • 54
  • 77
  • 1
    maybe you are getting a non-printing ASCII character – gtgaxiola Sep 30 '12 at 03:05
  • 3
    You're generating a character whose ASCII value is between 0 and 26, and these are all non-printing characters. If your intention was to print a random letter of the alphabet, then you should probably add 'A' to your integer instead of directly casting it to (char). – Dawood ibn Kareem Sep 30 '12 at 03:10
  • @DavidWallace you're right, it is returning a non-printing character, a little question, why should I add an 'A'? rather than just this? (char) rand.nextInt(25) + 65? – KyelJmD Sep 30 '12 at 07:24
  • Adding 65 is equivalent to adding 'A'. But your program will be easier for future maintainers to understand if you have 'A' in there. – Dawood ibn Kareem Sep 30 '12 at 07:34

1 Answers1

3

This is because rand.nextInt(27); is returning unprintable character codes. This will be evident if you change your code to return (char)65; for example.

techfoobar
  • 65,616
  • 14
  • 114
  • 135