gpt4 book ai didi

java - 我如何使用缓冲区读取器读取文件但使用java跳过注释

转载 作者:行者123 更新时间:2023-12-02 08:11:25 26 4
gpt4 key购买 nike

我编写了一个程序,它使用缓冲区读取器读取文件并将数据存储在字符串变量中。我如何修改它以使其跳过单行和多行注释?

这是我的代码:

import java.util.*;
import java.io.*;

public class IfCounter
{
public static void main(String[] args) throws IOException
{
// parameter the TA will pass in
String fileName = args[0];

// variable to keep track of number of if's
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");

// read from the text file
while (( line = reader.readLine()) != null)
{
stringBuilder.append(line);
stringBuilder.append(ls);
}

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

// create one last string to look for our valid if(s) in
// with ALL whitespace removed
String compareString = tempString.replaceAll("\\s","");

// check for valid if(s)
for (int i = 0; i < compareString.length(); i++)
{
if (compareString.charAt(i) == ';' || compareString.charAt(i) == '}' || compareString.charAt(i) == '{') // added opening "{" for nested ifs :)
{
i++;

if (compareString.charAt(i) == 'i')
{
i++;

if (compareString.charAt(i) == 'f')
{
i++;

if (compareString.charAt(i) == '(')
ifCount++;
} // end if
} // end if
} // end if

} // end for

// print the number of valid "if(s) with a new line after"
System.out.println(ifCount + "\n");

} // end main
} // end class

最佳答案

更改此:

    while (( line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}

对此:

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

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

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

您需要创建一个 boolean 方法,isLineAComment(String line)isLineAMultiLineCommentStartisLineAMultiLineCommentEnd但这对于你要做的。

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

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