如何使用Javaparser解析for循环? [英] How to parse a for-loop using Javaparser?

查看:291
本文介绍了如何使用Javaparser解析for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用javaparserfor-loop的不正确形式解析为正确形式.我的循环有5个参数:

I need using javaparser to parse uncorrect form of the for-loop to the correct form. My loop has 5 arguments:

  1. 循环索引(i);
  2. 索引的初始值.它可以是其他值(例如k)或int值(10);
  3. 循环不变式的值(3);
  4. 不变条件(>,<,> =或< =);
  5. 在每次循环运行后执行的操作(-或+将更改为i--或i ++).

我创建了两个类.第一个是不正确的循环,第二个是正确的循环(解析后).我首先决定编写这两个类,以检查解析前后代码的外观,然后编写用于解析的代码.但是我不确定这是否是一个好的开始,我代表了我的for-loop修正. 澄清:我想将Class.java中的代码解析为ClassAltered.java.

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.

循环不正确的第一堂课

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

推荐答案

[我是JavaParser的维护者]您可以对正则表达式使用搜索/替换,从而完全避免了JavaParser.不太漂亮,但是如果语法简单,则大多数情况下都可以使用.

[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.

这篇关于如何使用Javaparser解析for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆