首页 > 解决方案 > 如何在java中将char映射到int

问题描述

我对编程很陌生,无法解决以下问题。

我有一个 char 类型的坐标列表,我需要将其转换为数字(int 类型)。因此,例如 char a 应该是 int 0、char b - int 1 等。所以我使用 switch 语句构建了以下代码。我想将它作为方法调用,但我不断收到以下错误:此方法必须返回 int 类型的结果。有人可以解释我做错了什么吗?我也尝试过使用 return 而不是 int .. = 0; 但这也无济于事。

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

标签: javaswitch-statement

解决方案


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

推荐阅读