Android – converts a string array to an integer array

Since I couldn't find a simple way to convert a string array to an integer array, I looked for an example of the method, which is my final result:

private int[] convert(String string) {
    int number[] = new int[string.length()];

    for (int i = 0; i < string.length(); i++) {
        number[i] = Integer.parseInt(string[i]); // error here
    }
return number;
}

ParseInt needs a string, which is the string [i], but the error tells me that "the type of expression must be an array type, but it resolves to string"

I can't figure out what's wrong with my code

Editor: I'm an idiot. Thank you. All this is obvious

resolvent:

You are trying to read a string as if it were an array. I assume you try to pass a string at a time. To do this, use. Charat()

private int[] convert(String string) {
    int number[] = new int[string.length()];

    for (int i = 0; i < string.length(); i++) {
        number[i] = Integer.parseInt(string.charAt(i)); //Note charAt
    }
   return number;
}

However, if you want the string to be a string array, the array identifier will be omitted from the function prototype. Use the following corrected version:

private int[] convert(String[] string) { //Note the [] after the String.
    int number[] = new int[string.length()];

    for (int i = 0; i < string.length(); i++) {
        number[i] = Integer.parseInt(string[i]);
    }
   return number;
}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>