Вопрос

Hello i've built an application that will take a users input, then carry out some code dependant on the input. It all works right up until the line of code carried out within the switch case where i get ArrayIndexOutOfBoundsException: length=10; index=53
it should go through the loop 6 times to build up an array of characters that are put into kc
can anyone help?
code:

    char[] k = input.toCharArray();


    char[] p =   { '5', '6', '7', '8', '9', '1', '2', '3', '4', '5'};


    char[] kc = { '0', '0', '0', '0', '0', '0'};



    int i = 0;
    for (i = 0; i<6; i++) {


        switch (k[0]) {

            case '0':
                kc[i] = K0[p[i]]; k[0]++;
                break;

            case '1':
                kc[i] = K1[p[i]]; k[0]++;
            break;

            case '2':
                kc[i] = K2[p[i]]; k[0]++;
            break;

            case '3':
                kc[i] = K3[p[i]]; k[0]++;
            break;

            case '4':
                kc[i] = K4[p[i]]; k[0]++;
            break;

            case '5':
                kc[i] = K5[p[i]]; k[0]++;
            break;

            case '6':
                kc[i] = K6[p[i]]; k[0]++;
            break;

            case '7':
                kc[i] = K7[p[i]]; k[0]++;
            break;

            case '8':
                kc[i] = K8[p[i]]; k[0]++;
            break;

            case '9':
                kc[i] = K9[p[i]]; k[0]++;
            break;



        };

        if (k[0] == 10) {

            k[0] = 0;
        };

    }
Это было полезно?

Решение

The numeric value of a character that represents a number is not that number. Specifically, the char '0' is of value 48 not 0, '1' is 49 not 1, and so on through '9' being 57 not 9. Here's the ASCII table for reference.

You will need to convert the char value from p to a number by subtracting 48 from your char values. You don't have to remember that '0' is 48, just that the numeric char values are in order. This means that you can simply subtract '0'.

Here's an example of what you'll need to change; you can make other similar changes for other cases.

case '0':
    kc[i] = K0[ p[i] - '0' ]; k[0]++;
    break;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top