简体   繁体   中英

Easier way to assign numbers to letters

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...

如果您的余数小于或等于26,则可以使用-

codeLetter = (char) ('A' + remainder);

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);

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.

if(remainder <= 0)
    codeLetter = 'A';
else
    codeLetter = 'A' + remainder;

This covers the case where remainder is negative.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM