我正在研究一个java扫描程序项目。然后,扫描程序将扫描代码文件并识别所有标记,并将它们列为用户的输出。如果令牌无效,则扫描程序应提及给定令牌无效。 这是我的代码
try {
FileReader fin = null;
try {
fin = new FileReader(jTextField1.getText());
} catch (FileNotFoundException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader br= new BufferedReader(fin);
String line = null;
while ((line = br.readLine()) != null) {
// Get ending position
System.out.println(line);
StringTokenizer st = new StringTokenizer(line, "abcdefghijklmnopqrstuvwxyz[ =-+++--';().*{}[],!@#$%^&/]", true);
int caret=jTextArea1.getCaretPosition();
while(st.hasMoreTokens()){
switch(st.nextToken()){
case "++":
jTextArea1.insert("++"+" "+":Unary Operator "+"\n",caret);
break;
case "--":
jTextArea1.insert("--"+" "+":Unary Operator "+"\n",caret);
break;
case "!":
jTextArea1.insert("!"+" "+":Unary Operator "+"\n",caret);
break;
case "+":
jTextArea1.insert("+"+" "+":Airthmatic Operator "+"\n",caret);
break;
case "-":
jTextArea1.insert("-"+" "+":Airthmatic Operator "+"\n",caret);
break;
case "*":
jTextArea1.insert("*"+" "+":Airthmatic Operator "+"\n",caret);
break;
case "/":
jTextArea1.insert("/"+" "+":Airthmatic Operator "+"\n",caret);
break;
case "%":
jTextArea1.insert("%"+" "+":Airthmatic Operator "+"\n",caret);
break;
case "<<":
jTextArea1.insert("<<"+" "+":Rational Operator "+"\n",caret);
break;
case ">>":
jTextArea1.insert(">>"+" "+":Rational Operator "+"\n",caret);
break;
case "=":
jTextArea1.insert("="+" "+":Rational Operator "+"\n",caret);
break;
case "(":
jTextArea1.insert("("+" "+":Symbol "+"\n",caret);
break;
case "&":
jTextArea1.insert("&"+" "+":Conditional Operator "+"\n",caret);
break;
case "|":
jTextArea1.insert("|"+" "+":Conditional Operator "+"\n",caret);
break;
case ")":
jTextArea1.insert(")"+" "+":Symbol "+"\n",caret);
break;
case "{":
jTextArea1.insert("{"+" "+":Symbol "+"\n",caret);
break;
case "}":
jTextArea1.insert("}"+" "+":Symbol "+"\n",caret);
break;
case "[":
jTextArea1.insert("["+" "+":Symbol "+"\n",caret);
break;
case "]":
jTextArea1.insert("]"+" "+":Symbol "+"\n",caret);
break;
case ".":
jTextArea1.insert("."+" "+":Symbol "+"\n",caret);
break;
case ",":
jTextArea1.insert(","+" "+":Symbol "+"\n",caret);
break;
case ";":
jTextArea1.insert(";"+" "+":Symbol "+"\n",caret);
break;
case ":":
jTextArea1.insert(":"+" "+":Symbol "+"\n",caret);
break;
case "'":
jTextArea1.insert("'"+" "+":Symbol "+"\n",caret);
break;
default :
break;
这是我的输出http://s11.postimg.org/962xs85r7/Untitled.jpg 程序输出适用于所有括号和运算符,正如我在switch语句中提到的那样,但是我想要显示输出中显示的所有字符串,并且还提到它是字符串以及++, - 数字,但我如何使用字符串check和++, - switch语句中的数字。例如:system:string ab:string和输出中显示的所有字符串相同,谢谢
答案 0 :(得分:0)
您的问题是您无法在switch语句中使用正则表达式。 你可以做的是使用默认值。在默认情况下,您可以添加以下代码: if(str.matches(“[A-Za-z]”))
使用nextToken()时,要使用您需要保存的字符串: String str = st.nextToken();
正则表达式可能会根据您的假设而有所不同