-1

How can i ignore the comment statements that begin with "/*" and ends with "*/" for example: /*the problem is..*/ or /* problem is very difficult */ ,,i want to remove these statement when i reading java file line by line

public class filename1 {

      public static void main (String args[])

        {

    try {

      fileName = "C:\\NetBeansProjects\\filename\\src\\filename\\filename.java";

      FileReader fr = new FileReader(fileName);

     BufferedReader br = new BufferedReader(fr);

        line = br.readLine();

        while (line !=null) {


       for( int i=0;i<line.length();i++)

         {            
           b=line.indexOf("/",i);         

           ee=line.indexOf("*",i);         
           if(b!=-1 && ee!=-1)

           v=line.indexOf("*/",i);
             if (v==-1)
              line=" ";
                  }


                System.out.println(line);


                 line = br.readLine(); 
                          }}

                  catch (IOException e)
               {   
                e.printStackTrace();

                  }
                }
                }
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
user3449656
  • 15
  • 1
  • 4
  • 9
    Fundamentally, don't expect to be able to write a working Java parser in this little code. Consider string literals that contain `/*` for example. or lines that contain it more than once... – Jon Skeet Mar 01 '16 at 23:35
  • Try find an IDE or editor that folds block comments. Block comments can help you understand the meaning of methods, variables, etc, so removing them is absolutely not the best idea when your goal is to understand the program. Just fold it by default and you can unfold when you need to. – Xiongbing Jin Mar 01 '16 at 23:38
  • 1
    Unless you really want to write the parser yourself, try to use an existing Java source code parser library: http://stackoverflow.com/questions/1967987/how-to-generate-ast-from-java-source-code?rq=1 – Thilo Mar 01 '16 at 23:39
  • I don't write any parser ..I must do that manually. .when I reading file ..print all lines of file except the comment's statements... thanks for all. – user3449656 Mar 01 '16 at 23:43
  • 3
    You missed the point. If you want to accurately remove comments you must deal with several non-obvious scenarios such as multi-line commends, comments that contain the string `/*`, and Java strings that contain `/*`, such as `String xyz = "/*";`, which DOES NOT indicate a comment. At a minimum you will need to write a lexer that understands Java tokens. Not a full parser, but a lexer for Java is already complex enough. – Jim Garrison Mar 01 '16 at 23:52
  • Use a code editor with **syntax highlighting** – Arif Burhan Mar 02 '16 at 00:00
  • @JimGarrison @JonSkeet Agree. In addition, processing of `\uNNNN` escape sequences occurs **before** lexical analysis, so the text `\u002f\u002a This is a comment. */` actually is a comment. This is because `\u002f` is hex value for `/` and `\u002a` is the hex value for `*`. – Stuart Marks Mar 02 '16 at 00:07
  • 1
    Sounds like you need a simple state-machine where the states are "in block comment" and "not in block comment" – OneCricketeer Mar 02 '16 at 00:19
  • 2
    Why is everybody saying you must be careful with `/*` inside a comment? When you find the first `/*` that starts a comment, all you need to do is find the next occurrence of `*/` (or its `\u` equivalent) on this or a subsequent line - no need to look for a second `/*`. – Klitos Kyriacou Mar 02 '16 at 00:19
  • 1
    Would be easier if you read the file a few characters at a time (whitespace included) instead of line-by-line. – OneCricketeer Mar 02 '16 at 00:21

1 Answers1

-1

Simply include:

int index =  str.indexOf("/*");

while(index != -1) {
    str = str.substring(0, index) + str.substring(str.indexOf("*/")+2);
    index =  str.indexOf("/*");
}

Edit: Assuming that you have to account for fragments where you have a comment interrupted by the start or end of the string:
Edit2: Now.. Also assuming that you have to take into account for literal string "/*" or "*/"

str = str.replace("\"/*\"", "literal_string_open_comment");
str = str.replace("\"*/\"", "literal_string_close_comment");

int start =  str.indexOf("/*"), end = str.indexOf("*/");

while(start > -1 || end > -1) {
    if(start != -1) {
        if(end != -1) {
            if(end < start) {
                str = str.substring(end+2);
            } else {
                str = str.substring(0, start) + str.substring(end+2);
            }
        } else {
            str = str.substring(0, start);
        }
    } else {
        str = str.substring(end+2);
    }

    start =  str.indexOf("/*"); 
    end = str.indexOf("*/");
}

str = str.replace("literal_string_open_comment", "\"/*\"");
str = str.replace("literal_string_close_comment", "\"*/\"");
Maljam
  • 6,244
  • 3
  • 17
  • 30
  • 4
    Now try running this code on itself to see why it's not that "simple". – Andy Turner Mar 01 '16 at 23:40
  • If you mean that the "comment" section can start in a fragment and end in the next, that's just a simple addition of a block that checks `if(str.indexOf("*/") == -1) //deal with it` – Maljam Mar 01 '16 at 23:45
  • 4
    Nope, I mean that the `/*`s in this code aren't the start of comments (similarly for the `*/`s). – Andy Turner Mar 01 '16 at 23:47
  • For example;: the file I will read is : public class filename { int p=3; int c=p*p; System.out.print ( p); /* the problem is simple to resolve*/ }} so , I will read all these lines in file except this line /* the problem is simple to resolve*/ – user3449656 Mar 01 '16 at 23:59
  • I'm confused... this code (although it's a bit messy) removes any code that is bound by `/*` and `*/`, including the cases where the start or the end of the string is in the middle of a "comment", i.e. `*/` occurs first or there's an orphan `/*`. Isn't that what you're looking for? – Maljam Mar 02 '16 at 00:13
  • public class filename extends C //extends { public int d(int s) //njnjnjn { /*public String sequal(int month ) { String monthString; switch (month) { case 1: monthString = "January"; break case 2: monthString = "February";break; case 4: monthString = "April"; break; default: monthString = "Invalid month"; break; return (monthString); */ public static void main(String[] args) { filename ss=new filename(); int s=9; – user3449656 Mar 02 '16 at 00:21
  • This is an example to explain what i want...when for example in my file have blocks begin with /* and ends with */ i must be ignore it and read other lines that isn't comment but real line. – user3449656 Mar 02 '16 at 00:26
  • Yes that's what that code does... it removes blocks bound by `/*` THIS CODE IS REMOVED `*/` – Maljam Mar 02 '16 at 00:27
  • 1
    @user3449656 there's no such things as "lines that isn't comment but real line". Comments can appear at the start, in the middle or at the end of a line that has other valid Java code which presumably you _do_ want to keep. – Klitos Kyriacou Mar 02 '16 at 00:29
  • @user3449656 also in your original question you mention "comment statements" - there's no such thing. It's either a comment or a statement. – Klitos Kyriacou Mar 02 '16 at 00:30
  • @Maljam yes but it also removes blocks which are _not_ comments. E.g. `String s = "/*"; /* this is a comment */` is turned into `String s = "` thus turning valid Java code into invalid code. – Klitos Kyriacou Mar 02 '16 at 00:34
  • yes i am sorry,,this is exactly what i want ,,thanks for all ,,,,and thank you Maljam for your code ..... – user3449656 Mar 02 '16 at 00:40