---
title: "JavaCC的简单例子"
author: "winzenghua"
date: "2009-11-19T19:51:00Z"
tags: []
slug: "javacc"
draft: false
lastmod: "2009-11-19T19:51:00Z"
id: 987991
url: "https://java4gis.iteye.com/blog/987991"
---

JavaCC附带的例子是寻找匹配的花括号个数的，我写的例子在它的基础上稍微延伸，可以实现对多行的处理，每行的信息都能表现出来。

options{  
STATIC = false;  
}

PARSER\_BEGIN(Simple2)

public class Simple2 {  
public static int lineNumber = 0;

public static void main(String args\[]) throws ParseException {  
Simple2 parser = new Simple2(System.in);  
parser.Run();  
System.out.println("Total Line = "+ (lineNumber+1));//计算行数  
}

}

PARSER\_END(Simple2)

SKIP :  
{  
" "  
| "\\t"  
| "\\r"  
}

TOKEN:  
{  
&lt;NEWLINE : "\\n"&gt;//考虑到系统不同,仅选择对\\n标记  
{  
Simple2.lineNumber++;//因为此处是在TokenManager处理需要标识作用域  
}  
}

void Run():{}  
{  
( Input() )\*&lt;EOF&gt;  
}

void Input() :  
{  
int count;  
}  
{  
( count = MatchedBraces() )+ (&lt;NEWLINE&gt;)*  
{System.out.println("This line:" + count);}  
}

int MatchedBraces() :  
{ int nested\_count = 0;}  
{  
"{" \[ nested\_count = MatchedBraces() ] "}"  
{ return ++nested\_count; }  
}

不足的地方时，如此写法会出现冗余代码，原因在MatchedBraces函数中的花括号出现，因此待我研究明白LOOKAHEAD之后再做改进。