0

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

Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
Amey Gupta
  • 57
  • 1
  • 10

4 Answers4

2

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]
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Romy
  • 272
  • 2
  • 11
0

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.

happyHelper
  • 119
  • 8
0

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

Laerte
  • 7,013
  • 3
  • 32
  • 50
0

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);
randomraccoon
  • 308
  • 1
  • 4
  • 14