1

Here is part of my code:

 // randomly create lowercase ASCII values
 int rLowercase1 = random.nextInt(122) + 97;

 // convert ASCII to text
 System.out.print((char)rLowercase1);

When I run my program, it displays symbols instead of lowercase letters. Is there any way that I can fix this so that it displays lowercase letters?

word word
  • 447
  • 3
  • 7
  • 9

4 Answers4

4

How about

rLowercase1 = 'a' + random.nextInt('z' - 'a' + 1);

Number of letters in alphabet can be calculated with 'z' - 'a' + 1 = 25 + 1 = 26.

Since random.nextInt(n) will return value from range [0; n) - n is excluded - it means that you can get 'a'+0 = 'a' as minimal value and 'a'+25 = 'z' as max value.

In other words your range of characters is from 'a' till 'z' (both included).

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • 2
    Avoid magic numbers (http://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad). The question is another example of why magic numbers are bad. – Jonathan Rosenne Nov 02 '13 at 16:30
0

Change your code as:

int rLowercase1 = random.nextInt(26) + 97; // it will generate a-z
Masudul
  • 21,823
  • 5
  • 43
  • 58
0

There are only 26 lower case letters:

int rLowercase1 = random.nextInt(26) + 97;
Henry
  • 42,982
  • 7
  • 68
  • 84
0

If you want only the 26 unaccented Latin letters, Change 122 to 26:

int rLowercase1 = random.nextInt(26) + 97;

I think the meaning of this is a little clearer if written like this:

int rLowercase1 = 'a' + random.nextInt(26);
Boann
  • 48,794
  • 16
  • 117
  • 146