|
For example, def index(str, substr) {
for (int i = 0; i < str.length(); i++) {
int k
for (k = 0; k < substr.length() && substr[k] == str[i + k]; k++) print ""; // Now I have to express 'do nothing' through print ""
if (k == substr.length())
return i;
}
return -1;
}
s1 = "abcdef"
s2 = "cde"
println index(s1, s2)
Just use: for(...) {} By the way, If I omit the initialization part in for loop like the following code: int k = 0; for (; k < 10; k++) { println k; } failed too if we are going to have C/C++/Java style for loops then having ; as the body has to work. I am not sure it is acceptable to say "you must use {} as the body". An interesting question is whether "for ( . . . ) \n" should be valid since Groovy has optional semicolons. Jochen, can you provide feedback on this issue. Let me know if you are opposed to the change but if not, check if the patch looks OK. I am happy if you want to apply, otherwise assign to me and I will apply with appropriate tests. To answer Russel's question, currently (and with the attached patch) a for without a semicolon "takes the next line" as the statement, e.g.: int k for (k=0; k < 3; k++) println 'inner' + k println 'outer' + k yields: inner0 inner1 inner2 outer3 and of course, adding the semicolon on to the for loop will yield: inner3 outer3 which is a common garden variety bug which would be good to help eliminate. Without the patch we eliminate it by providing a horrible error message. With the patch we let it go but it is most likely to catch people who continue to use semicolons when doing Groovy, i.e. if you don't normally use semicollons and you do have one at the end of the for loop you are likely to intentionally rather than accidentally want it. I think with the patch is the preferred approach. Also, just noted that while loops have the same limitation. I'll extend the patch to also allow empty while statements tomorrow unless I hear that this isn't desirable. I don't think it would normally be good style but I don't think it should be illegal. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
By the way, what's the use of a for loop which does nothing at all???