我对所有关键字/保留字都有一个ArrayList
,但是当打印输出时会打印出重复的关键字,我知道我可以使用HashSet
来消除重复(I'我们尝试过所有这些都没有,到目前为止没有工作)。但我认为contains
方法负责打印重复项。
有关contains
方法的替代方案的任何建议吗?
我顺便创建一个词法分析器,这是样本输入和输出
的ArrayList:
ArrayList<String> keywords = new ArrayList<>(Arrays.asList("auto","case","char","const","continue","default",
"do","double","else","break","enum","extern","float","for","goto",
"if","int","long","register","return","short","signed",
"sizeof","static","struct","switch","typedef","union",
"unsigned","void","volatile","while","then","int","endif"));
显示代码:
System.out.print("Keywords:");
for(int i =0; i<testarray.size(); i++){
String gg = testarray.toString().replace(",","").replace("[","").replace("]","");
String[] key = gg.trim().split(" ");
String gg1 = key[i];
if(keywords.contains(gg1)){
System.out.println(gg1+" ");
}
}
输入:
{
int a[3],t1,t2;
t1= 2 ; a[0]= 1; a[1]= 2; a[t1]= 3;
t2= - (a[2] + t1 * 6 ) / (a[2] - t1);
if t2 > 5
then
print ( t2 );
else {
int t3 ; t3 = 99 ; t2 = -25 ;
print(- t1 +t2 * t3);
} endif
}
输出: 关键字:int if then else int endif
阅读文件:
while((line = bufferedReader.readLine()) != null) {
test = line.split(" ");
testarray.addAll(Arrays.asList(test));
}
答案 0 :(得分:0)
我觉得你无所事事地做着复杂的事情:
<强>的ArrayList:强>
ArrayList<String> keywords = Arrays.asList("auto","case","char","const","continue","default",
"do","double","else","break","enum","extern","float","for","goto",
"if","int","long","register","return","short","signed",
"sizeof","static","struct","switch","typedef","union",
"unsigned","void","volatile","while","then","int","endif");
显示代码:
Set<String> keys = new HashSet<>();
for (String key : testarray) {
if(keywords.contains(key)) {
keys.add(key);
}
}
System.out.print("Keywords:");
for (String key : keys) {
System.out.println(key + " ");
}