Samuel Makanheni
Samuel Makanheni

Reputation: 21

Representing alphabets as numbers

can someone help please? I'm completely new to Java Programming and I need to represent alphabets as numbers such that I can perform operations (like matching two numbers) with numbers instead of alphabets.E.g. A = 1; B = 2; c = 3;... Many thanks

Upvotes: 2

Views: 7097

Answers (3)

arminb
arminb

Reputation: 2093

Considering that you're new to programming, you have to know that there is something called ASCII Code. This code describes which character is how encoded. As you can see the charachter 'a' is represented by the number 97. So in Java this

System.out.println((char)(97));

would print the character 'a'. The (char) is a so called cast. That means the number 97 is "forced" to be shown as a character. Vice versa you can do

System.out.println((int)'a');

This forces the character 'a' to be shown as its ASCII-number value 97.

So if you want to represent the characters from a to z by 1-26 you have to do:

char yourChar = 'z';
int yourCharInt = (int)yourChar - (int)'a' + 1;

Upvotes: 3

falsarella
falsarella

Reputation: 12437

Create conversor methods like these:

public class Test {
    public static void main(String[] args) {
        Test t = new Test();

        System.out.println(t.alphabetToNumber('A'));
        System.out.println(t.numberToAlphabet(1));
    }

    public int alphabetToNumber(char a) {
        return a - 64;
    }

    public char numberToAlphabet(int i) {
        return (char) (i + 64);
    }
}

Upvotes: 2

Karis
Karis

Reputation: 512

System.out.println((int)'A');

will give you 65 (ascii code for A is 65)

System.out.println((int)'A' - 64);

will offset the number to 1.

If you want the lower 'a' to print out to 1 as well using the above method, simply turn that to uppercase with Character.toUppserCase('a');

Upvotes: 3

Related Questions