2012-02-27 25 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 if」語句,然後進入下一行。

嘗試使用3 if語句,而不是一個「如果」和兩個「否則,如果」 S

的問題是,對於任何線,就可以順利通過ONLY ONE條件語句的方式,你有它編碼。這意味着如果你有一個註釋AND int在同一行上,它只會找到int,然後繼續下一次循環迭代。

+0

哇。多麼簡單的修復。非常感謝! – kmaz13 2012-02-27 04:03:25