这是我的代码。
while(in.hasNext()){
String line = in.nextLine();
in.hasNextLine();
if (line.length() >0){
int k = -1;
k = -1;
while(true){
k = line.indexOf('\n' + "{", k+1);
if(k<0)break;
bracketNewLine++;
}
k = -1;
while(true){
k = line.indexOf(" {", k+1);
if(k<0)break;
bracketWithSpace++;
}
}
}
如果我有文本文件
if (...) {
}
and
if (...)
{
}
输出是:
感谢您的回答。
答案 0 :(得分:0)
您逐行阅读文件。因此,没有机会在同一个String中找到后跟另一个字符的字符\n
。因此,永远不会找到'\n' + "{"
。
您可以使用简单的正则表达式执行此操作:
for(String line : Files.readAllLines(Paths.get("/path/to/input.txt"))) {
if(line.matches("\\{.*")) {
bracketNewLine++;
}
if(line.matches(".* \\{")) {
bracketWithSpace++;
}
}
答案 1 :(得分:0)
您可以使用这样的正则表达式:
String patternInLine = ".+\\{$";
String patternNewLine = "^\\{":
Pattern p1 = new Pattern(patternInLine);
Pattern p2 = new Pattern(patternNewLine);
while(in.hasNext()) {
String line = in.nextLine();
in.hasNextLine();
Matcher m1 = p1.match(line);
Matcher m2 = p2.match(line);
if(m1.match())
{
//inLine++;
}
else if (m2.match())
{
//newLine++;
}
else
{
//other cases
}
}
答案 2 :(得分:0)
使用nextLine()
方法时,您已逐行获取源代码。您应该做的唯一事情是使用现有的String方法检查每个循环中的那些行:startsWith()
,endsWith()
。如果我们假设您正确地在每个循环中获取行字符串,那么while块内部应该是这样的:
if(line.startsWith("{"))
bracketNewLine++;
if(line.endsWith("{"))
bracketWithSpace++;
P.S.1 hasNext()
方法并不能保证我们还有一条新线。
P.S.2搜索具有固定大小空间的字符串不是一种真正的方法。您可以使用正则表达式而不是:^[\s]*{