gpt4 book ai didi

java - 如何使用缓冲区阅读器跳过注释?

转载 作者:行者123 更新时间:2023-11-30 04:59:28 25 4
gpt4 key购买 nike

我编写了以下程序来从文件中读取并跳过注释,它适用于单行注释,但不适用于多行注释。有谁知道为什么?我不需要担心字符串中的“//”。并且只有java注释,即“//”和“/* */”

代码:

import java.io.*;

public class IfCounter2
{
public static boolean lineAComment(String line)
{
if (line.contains("//"))
return true;

return false;
}

public static boolean multiLineCommentStart(String line)
{
if (line.contains("/*"))
return true;

return false;
}

public static boolean multiLineCommentEnd(String line)
{
if (line.contains("*/"))
return true;

return false;
}

public static void main(String[] args) throws IOException
{
String fileName = args[0];

int numArgs = args.length;

int ifCount = 0;

// create a new BufferReader
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");

line = reader.readLine();
// read from the text file
boolean multiLineComment = false;

while (( line = reader.readLine()) != null)
{
if (!multiLineCommentStart(line))
{
multiLineComment = true;
}

if (multiLineComment) {
if (!multiLineCommentEnd(line))
{
multiLineComment = false;
}
}

if (!lineAComment(line) && !multiLineComment)
{
stringBuilder.append(line);
stringBuilder.append(ls);
}
}


// create a new string with stringBuilder data
String tempString = stringBuilder.toString();
System.out.println(stringBuilder.toString());

}
}

最佳答案

只有当 !multiLineCommentStart(line) 为 true 时,才将 multiLineComment 设置为 true - 也就是说,只要该行不包含 /* .

关于java - 如何使用缓冲区阅读器跳过注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7396331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com