Re: [問題] 檢查保留字的程式
看錯了>"<
從那裡拔豆, 就要從那裡站起來。
除了道歉之外,俺附上自己實作的版本。
對不起啦>"<
實作策略:
1. 先建構一個能比對keyword的基本類別Keyword
2. 利用字串切割split組成token list
===========================================================
keyword檔
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
false
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while
===========================================================
2. Keyword類別
import java.io.BufferedReader;
public class Keyword extends HashSet {
public Keyword() {
try {
BufferedReader reader = new BufferedReader(new FileReader(
"keyword"));
String temp;
while ((temp = reader.readLine()) != null) {
this.add(temp.trim());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args){
System.out.println(new Keyword().contains("goto"));
}
}
===========================================================
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Check {
public static void main(String[] args) {
Keyword keyword = new Keyword();
String userInput = "asfdasdfsafd\nsfdajsfkajknavgotokljdf aksdfad
faskdflaksfd aslkfa sldflaskjdfaskj"
+ "dflaskdf \n goto\nif\njkjsk if(";
Iterator tokens = Arrays.asList(
userInput.split("[\\n\\ \\(\\),\\.\\r]+")).iterator();
String curToken = null;
while (tokens.hasNext()) {
curToken = (String) tokens.next();
if (keyword.contains(curToken)) {
System.out.println("發現keyword [" + curToken + "]");
} else {
System.out.println(curToken + "並沒有什麼可疑之處");
}
}
}
}
===========================================================
asfdasdfsafd並沒有什麼可疑之處
sfdajsfkajknavgotokljdf並沒有什麼可疑之處
aksdfad並沒有什麼可疑之處
faskdflaksfd並沒有什麼可疑之處
aslkfa並沒有什麼可疑之處
sldflaskjdfaskjdflaskdf並沒有什麼可疑之處
發現keyword [goto]
發現keyword [if]
jkjsk並沒有什麼可疑之處
發現keyword [if]
--
夫兵者不祥之器物或惡之故有道者不處君子居則貴左用兵則貴右兵者不祥之器非君子
之器不得已而用之恬淡為上勝而不美而美之者是樂殺人夫樂殺人者則不可得志於天下
矣吉事尚左凶事尚右偏將軍居左上將軍居右言以喪禮處之殺人之眾以哀悲泣之戰勝以
喪禮處之道常無名樸雖小天下莫能臣侯王若能守之萬物將自賓天地相合以降甘露民莫
之令而自均始制有名名亦既有夫亦將知止知止可以不殆譬道之在天下163.26.34.20海
討論串 (同標題文章)
java 近期熱門文章
PTT數位生活區 即時熱門文章