1

I have the below string declaration and i am using the string in for loop:

String[] values = new String["A","B","C"]
for (int i = 0, length = values.length; i < length; i++)
    {
        getData(values[i], i, length);
    }

Throwing an error "unexpected token: = @" at for loop line.

3 Answers 3

4

Groovy is different for creating string arrays, you'd do

String[] values = ['A', 'B', 'C']

You could also do what you're trying to do with

def values = ​["A","B","C"]
values.eachWithIndex { item, idx -> 
    getData(item, idx, values.size())
}​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Sign up to request clarification or add additional context in comments.

3 Comments

i tried the String[] values = ['A', 'B', 'C'] declaration but it still throws the same error in the for loop,
Yeah, for loops in groovy don't accept multiple variables as in Java
The eachWithIndex above should do the same as you're trying with the for loop
0

If you want to write valid Java, you have to initialize your array with the values wanted in curly braces and that looks like:

String[] values = new String[]{"A","B","C"};
for (int i = 0, length = values.length; i < length; i++) {
    getData(values[i], i, length);
}

If you want to do that in Groovy, just use:

String[] values  = [ 'A', 'B', 'C' ]
values.eachWithIndex { v, i ->
  getData(v, i, values.size())
}

2 Comments

Sorry, just saw the java tag which was still there at the beginning, I've updated my answer and also put the Groovy solution.
Sorry, just saw the java which was once there on your question. I'll updated my answer now also with the Groovy part.
-1

In your code example you did not use a semicolon after the initialization of the for loop. for example,

for(var i= 0; i

compiling without the semicolon will give you an error, not initializing the I variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.