views:

191

answers:

3

I'm relatively new to Java coding, and was looking for some help. I have a capital letter defined in a variable string, and I want to output the next and previous letters in the alphabet. For example, if the variable was equal to C, I would want to output B and D.

Thanks in advance for any help.

+2  A: 

If you are limited to the latin alphabet, you can use the fact that the characters in the ASCII table are ordered alphabetically, so:

System.out.println((char) ('C' + 1));
System.out.println((char) ('C' - 1));

outputs D and B.

What you do is add a char and an int, thus effectively adding the int to the ascii code of the char. When you cast back to char, the ascii code is converted to a character.

Bozho
+4  A: 

One way:

String value = "C";
int charValue = value.charAt(0);
String next = String.valueOf( (char) (charValue + 1));
System.out.println(next);
Kevin
Thanks, that's exactly what I was looking for!
raleighJ
But this code includes all char. not only letters, you will get a surprise when you will reach Z. (numbers etc..)Also, this assumes you start at a letter.
Marc
raleighJ
+3  A: 

Well if you mean the 'ABC' then they split into two sequences a-z and A-Z, the simplest way I think would be to use a char variable and to increment the index by one.

char letter='c';

letter++;   (letter=='d')

same goes for decrement:

char letter='c';

letter--; (letter=='b')

thing is that the representation of the letters a-z are 97-122 and A-Z are 65-90, so if the case of the letter is important you need to pay attention to it.

hope this helps,

Adam.

TacB0sS