请求协助完善移除Java代码三种注释的程序
Solution to Strip All Comment Types in Java
Here's a complete implementation that handles all three comment types (line //, block /* */, and Javadoc /** */ which is just a variant of block comments):
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class StripComments { public static void main(String[] args) throws IOException { new StripComments(); } public StripComments() throws IOException { boolean inBlockComment = false; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = reader.readLine()) != null) { StringBuilder processedLine = new StringBuilder(); int i = 0; int length = line.length(); while (i < length) { if (inBlockComment) { // Check for end of block comment if (i < length - 1 && line.charAt(i) == '*' && line.charAt(i+1) == '/') { inBlockComment = false; i += 2; // Skip both '*' and '/' } else { i++; // Ignore characters inside block comment } } else { // Check for start of block comment (including Javadoc /**) if (i < length - 1 && line.charAt(i) == '/' && line.charAt(i+1) == '*') { inBlockComment = true; i += 2; } // Check for line comment else if (i < length - 1 && line.charAt(i) == '/' && line.charAt(i+1) == '/') { break; // Skip remaining characters in the line } // Add regular characters to output else { processedLine.append(line.charAt(i)); i++; } } } // Print the processed line (preserves empty lines if needed) System.out.println(processedLine.toString()); } reader.close(); } }
How It Works
- Multi-Line Block Comment Handling: The
inBlockCommentboolean tracks whether we're inside a/* */comment (including Javadoc/** */). This ensures comments spanning multiple lines are fully removed instead of leaving partial content. - Line Comment Handling: When a
//is detected, we stop processing the rest of the line since line comments only affect content from that point onward. - Character-by-Character Processing: By iterating through each character individually, we avoid missing edge cases like comments appearing mid-line or adjacent to valid code.
Limitation to Note
This implementation doesn't account for comment markers inside string literals (e.g., "/* this is part of a string, not a comment */"). If you need to handle this scenario, you'd need to add an additional state variable to track when you're inside a string and skip comment detection during that time.
内容的提问来源于stack exchange,提问作者Jon Kon
相关产品推荐
相关产品推荐

