1

I am new to programming in java (and programming in general), and was wondering if there was an easier way to say this. Basically, I'm just trying to assign numbers to letters. This is the only way I know of how to do this, but I'm sure there's a much simpler way to do this in java. Thank you for any help the community can give me.

Note: codeLetter is a char, and remainder is an int.

if (remainder <= 0)
{
    codeLetter = 'A';
}
else if (remainder <= 1)
{
    codeLetter = 'B';
}
else if (remainder <= 2)
{
    codeLetter = 'C';
}
else if (remainder <= 3)
{
    codeLetter = 'D';
}
else if (remainder <= 4)
{
    codeLetter = 'E';
}

etc...

Bob Dave
  • 35
  • 2
  • 6

4 Answers4

10

If your remainder is less then or equal to 26, you could use -

codeLetter = (char) ('A' + remainder);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
4

If letter assignments are alphabetical, you can rely on the fact that UNICODE code points for Latin letters are alphabetized. If you need to define an arbitrary assignment, you could use a String as a "key": put the letters that you want to encode in a string, ordering them by remainder, and use charAt to extract the corresponding letter:

// Let's say you want to re-order your letters in some special way
String key = "QWERTYUIOPASDFGHJKLZXCVBNM";

// Now you can obtain the letter like this:
char letter = key.charAt(remainder);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

Try using switch. Or use Character.getNumericValue() if you don't need to assign the numeric value yourself.

Or see this post which may be the most appropriate: making use of the ASCII representation of the characters.

Community
  • 1
  • 1
eebbesen
  • 5,070
  • 8
  • 48
  • 70
  • 1
    +1 for a readable solution that new users can understand. The other solutions (involving casting and adding chars to integers) are very cryptic to beginniners. – gnomed Sep 22 '14 at 20:14
1
if(remainder <= 0)
    codeLetter = 'A';
else
    codeLetter = 'A' + remainder;

This covers the case where remainder is negative.

cppprog
  • 804
  • 3
  • 12
  • 22