I need using javaparser to parse uncorrect form of the for-loop to the correct form. My loop has 5 arguments:
index of the loop (i);
initial value of the index. It can be other value (for example, k) or int value (10);
value of the loop invariant (3);
condition of the invariant (>, = or <=);
operation, performed after each loop run (- or + will be changed to i-- or i++).
I've created two classes. The first one is with the uncorrect loop and the second one is with the correct loop (after parsing). I decided at first to write this two classes to check how should look the code before and after the parsing and then writing the code for parsing. But I'm not sure that it's a good start and I represented my for-loop correctry.
Clarify: I want to parse the code from Class.java to the ClassAltered.java.
The first class with uncorrect loop:
public class Class {
public static void main(String[] args) {
test1();
test2();
}
public static void test1() {
FOR(i, 10, 3, >, -);
System.out.println("FOR(i, 10, 3, >, -) test passed");
}
public static void test2() {
FOR(j, 0, 10, <=, +);
System.out.println("FOR(j, 0, 10, <=, +) test passed");
}
}
The second class with the correct loop:
public class ClassAltered {
public static void main(String[] args) {
test1();
test2();
}
public static void test1() {
for(int i=10; i > 3; i--);
System.out.println("FOR(i, 10, 3, >, -) test passed");
}
public static void test2() {
for(int j=0; j<= 10; j++);
System.out.println("FOR(j, 0, 10, <=, +) test passed");
}
}
解决方案
[I am the maintainer of JavaParser] You could use a search/replace with regular expressions, avoiding JavaParser alltogether. Not pretty, but if the syntax is simple it will work most of the time.