Zsa_Sza
Zsa_Sza

Reputation: 15

how to map char to int in java

I'm very new to programming and can't resolve the following problem.

I have a list of coordinates in type char that I need to transfer to numbers (type int). So for example char a should be int 0, char b - int 1 etc. So I build the following code using a switch statement. I want to call it as a method but I keep getting the following error: this method must return a result of type int. Could somebody please explain what I'm doing wrong? I've also tried using return instead of int .. = 0; but that didn't help either.

    int x () {
        char ch = 'c';
        switch (ch)
        { 
        case 'a': 
            int a = 0;
            break; 
        case 'b': 
            int b = 1;
            break; 
        case 'c': 
            int c = 2;
            System.out.println(c); 
            break; 
        case 'd': 
            int d = 3;
            break; 
        case 'e': 
            int e = 4;
            break; 
        case 'f': 
            int f = 5;
            break; 
        case 'g': 
            int g = 6;
            break; 
        case 'h': 
            int h = 7;
            break; 
        }   
}

Upvotes: 1

Views: 4064

Answers (2)

Hadi Moloodi
Hadi Moloodi

Reputation: 639

If your chars are just the same you mentioned you can use something like this.

static int toNumber(char chr) {
        return (chr - 97);
    }

The concept is this: a char is encoded as a byte, which is a number. Check out a related ASCII table where you can see that 'a' has the value 97 (decimal), 'b' has 98... So if we subtract 97 from all our chars we can reach the desired values.


    char   byte(decimal)   char value -97
    a        97                  0
    b        98                  1
    ...      ...                ...
    z        122                 24

But the problem with your function is the fact that the return statement was missing. You can make it work by changing it to this

int x() {
    char ch = 'c';
    int value = 0;
    switch (ch) {
        case 'a':
            value = 0;
            break;
        case 'b':
            value = 1;
            break;
        case 'c':
            value = 2;
            System.out.println(c);
            break;
        case 'd':
            value = 3;
            break;
        case 'e':
            value = 4;
            break;
        case 'f':
            value = 5;
            break;
        case 'g':
            value = 6;
            break;
        case 'h':
            value = 7;
            break;
    }
    return value;
}

Upvotes: 2

Sanower Tamjit
Sanower Tamjit

Reputation: 54

You can get it different ways.

int x = Character.getNumericValue('a');  

or,

char a = 'a';
int x = a;

or,

int x = Integer.parseInt(String.valueOf('a')); 

Upvotes: 0

Related Questions