Convert String array to an array of integers

Since I could not find an easy way to convert my string array to an integer array, I was looking for an example for a method, and here is what I got:

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 requires a string, which is the string [i], but the error tells me: "The type of the expression must be an array type, but it is allowed for String"

I can’t understand what the problem is with my code.

EDIT: I'm an idiot. Thank you, everything was obvious.

+3
source share
4 answers

You are trying to read a string as if it were an array. I assume that you are trying to go through a line one character 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;
}

, , . :

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

. :

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

- String, String. String [i]. String, 'String.charAt(..)' 'String.substring(..)'. , charAt(..) char, .

+2

Arrays.asList( YourIntArray ) arraylist

Integer[] intArray = {5, 10, 15}; // cannot use int[] here
List<Integer> intList = Arrays.asList(intArray);

, :

List<Integer> intList = new ArrayList<Integer>(intArray.length);

for (int i=0; i<intArray.length; i++)
{
    intList.add(intArray[i]);
}

:

List<Integer> intList = new ArrayList<Integer>(Arrays.asList(intArray));

. #

0

All Articles