2012-02-27 4 views
3

他のJavaファイルを通り、クラス名、int変数名、およびコメントを表示できるクラスを作成する助けが必要です。別のファイルのクラス名、Int変数、およびコメントの出力

私はここで解析しようとしているテストクラスを持っています。

public class Test { 
    private int x; 
    private int y; 
    private String s; 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     // more comments 
     int l; //local variable 
     l = 0; 
    } 
} 

私が取得しているよ出力:

The Class name is : Test 
There is an int variable named: x 
There is an int variable named: y 
Comment contains: TODO Auto-generated method stub 
Comment contains: more comments 
There is an int variable named: l 
Comment contains: local variable 

ここでは、私が今持っているクラスのコードです:

import java.io.BufferedReader; 
import java.io.DataInputStream; 
import java.io.FileInputStream; 
import java.io.InputStreamReader; 

class ExtractJavaParts { 

    public static void main(String args[]){ 

     try{ 
      // Open the file that is the first 
      // command line parameter 
      FileInputStream fstream = new FileInputStream("src/Test.Java"); 

      // Get the object of DataInputStream 
      DataInputStream in = new DataInputStream(fstream); 
      BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
      String strLine; 

      //Read File Line By Line    
      while ((strLine = br.readLine()) != null){ 
       // Print the content on the console 
       if (strLine.contains("class")){ 
        System.out.println ("The class name is: " + strLine.substring(strLine.indexOf("class ") + 6, strLine.indexOf("{"))); 
       } 
       else if (strLine.contains("int")){ 
        System.out.println("There is an int variable named: " + strLine.substring(strLine.indexOf("int ") + 4, strLine.indexOf(";"))); 
       } 
       else if (strLine.contains("//")){ 
        System.out.println("Comment contains: " + strLine.substring(strLine.indexOf("//") + 2)); 
       } 
      } 

      //Close the input stream 
      in.close(); 
     } 

     catch (Exception e){ 
      //Catch exception if any 
      System.err.println("Error: " + e.getMessage()); 
     } 
    } 
} 

これは、現在出力されます。

The class name is: Test 
There is an int variable named: x 
There is an int variable named: y 
Comment contains: TODO Auto-generated method stub 
Comment contains: more comments 
There is an int variable named: l 

今のところプログラムはpコードの後に​​発生するコメントを書き留めてください。あなたが望む出力を得るために提供できるあらゆる助けは大いに感謝されます。本当にありがとう!

答えて

1

問題は、コードにint型のコメントが続くことです。

この行が読み込まれると、最初のelse else文に入り、次の行に進みます。

代わりに一つの「もし」と2のif文問題は任意の行のために、それはONLY ONE条件文を通じてあなたはそれがコード化されてきた道を行くことができるということであるS

「他の場合は、」3を使用してみてください。これは、同じ行にintを見つけ、ループの次の繰り返しに進むとのコメントがある場合を意味します。

+0

より多くのオプションを--has。何が簡単な修正。どうもありがとうございます! – kmaz13

0

このアプローチは遠くでは機能しません。 Javaソースファイルを理解するパーサーが必要です。あなたはおそらく、ソースコードを処理する多くのオープンソースツールから始めるでしょう。例えば ​​- javancssまたはcheckstyleまたはjavaparser

この回答 - Java : parse java source code, extract methodsうわー

関連する問題