Amey Gupta
Amey Gupta

Reputation: 57

How do you turn a number into its matching letter?

If I had the number 1, and it was user-submitted, would there be a java function to turn it into A? Similarly with B, how do I turn it into 2 (opposite)?

Upvotes: 0

Views: 318

Answers (4)

Romy
Romy

Reputation: 272

You could create an array with all the letters of the alphabet, then get the letter like this:

Array alphabet

int inputNumber = -input- 

and with this you will get your letter:

alphabet[inputNumber-1]

Upvotes: 2

randomraccoon
randomraccoon

Reputation: 308

Every char has an associated numeric value. Capital letters are different from lowercase letters, and symbols have numeric values as well. To find the numeric value of a char, just check an ASCII table. Or use:

char thisChar = 'A';
int charValue = (int) thisChar; // returns 65
char thisChar = 'a';
int charValue = (int) thisChar; // returns 97

Long story short, morgano's comment is correct. The correct line in this case would be:

// save user input as int number
char letter = (char)(number + 64);

Upvotes: 0

Laerte
Laerte

Reputation: 7083

This will probably solve your problem:

public static void main(String[] args) {
    System.out.println("1: " + numberToLetter(1));
    System.out.println("26: " + numberToLetter(26));
    System.out.println("a: " + letterToNumber('a'));
    System.out.println("z: " + letterToNumber('z'));
}

public static char numberToLetter(int number) {
    return (char)((byte)number+(byte)96);
}

public static byte letterToNumber(char letter) {
    return (byte)((byte)letter - (byte)96);
}

Hope it helps...

Upvotes: 0

happyHelper
happyHelper

Reputation: 119

You need to work with ASCII values. For example, A has a value of 65, B has 66 and so on. So you would get in the input and add 64 to it to get the respective character. I would suggest going through ASCII values.

Upvotes: 0

Related Questions