3

Since I couldn't figure out an easy way to convert my string array into an integer array, I looked up an example for a method and here is what I ended up with:

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 what string[i] is but the error tells me "The type of the expression must be an array type but it resolved to String"

I can't figure out what is the problem with my code.

EDIT: I'm an idiot. Thanks all it was obvious.

4 Answers 4

8

You're trying to read a string as if it were an array. I assume you're trying to go through the string one character at a time. To do that, 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;
}

If you expect the string to be an array of strings, however, you left out the array identifier in 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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

The IDE tells me it should be Integer.parseInt(String.valueOf(string.charAt(i)))
4

You have an error in your code. Use this code:

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

Comments

2

Your method's parameter is a String and not a String array. You cannot access elements in a String with string[i]. If you want to actually get a single character from a String, use 'String.charAt(..)' or 'String.substring(..)'. Note that charAt(..) will return a char but those are easy enough to convert to Strings.

Comments

0

Use Arrays.asList( YourIntArray ) to create arraylist

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

Alternatively, to decouple the two data structures:

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

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

Or even more:

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

.#this is worked for me

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.