這個代碼分析數字和運營商只我需要它來分析字母只,並把其他事情無效我應該做些什麼細節我從教程網站得到這段代碼,並修改它,但沒有結果。詞法分析在Java中的字母
package lexical;
public class Tokenizer {
int pos;
char[] expression;
Tokenizer(String expression) {
this.expression = expression.toCharArray();
this.pos = 0;
}
enum Type { OPERATOR, LITTER, UNKNOWN }
class Lexeme {
String type, token;
Lexeme(String type, String token) {
this.type = type;
this.token = token;
}
}
Lexeme getNextToken() {
StringBuilder token = new StringBuilder();
boolean endOfToken = false;
Type type = Type.UNKNOWN;
while (!endOfToken && hasMoreTokens()) {
while(expression[pos] == ' ' && hasMoreTokens())
pos++;
switch (expression[pos]) {
case '+':
case '-':
case '*':
case '/':
if(type != Type.LITTER) {
type = Type.OPERATOR;
token.append(expression[pos]);
pos++;
}
endOfToken = true;
break;
case ' ':
endOfToken = true;
pos++;
break;
default:
if(Character.isDigit(expression[pos]) || expression[pos] == '.') {
token.append(expression[pos]);
type = Type.LITTER;
} else {
System.out.println("Systax error at position: " + pos);
}
pos++;
break;
}
}
return new Lexeme(type.name().toLowerCase(), token.toString());
}
boolean hasMoreTokens() {
return pos < expression.length;
}
public static void main(String[] args) {
String expression = "54+18+5";
Tokenizer tokenizer = new Tokenizer(expression);
while (tokenizer.hasMoreTokens()) {
Lexeme nextToken = tokenizer.getNextToken();
System.out.print("Type: " + nextToken.type + "\tLexeme: " + nextToken.token + "\n");
}
}
}
我努力,因爲你發佈你的答案,但沒有 你能不能請張貼檢查所有字母和什麼是所有代碼無效 在此先感謝 – user3513220 2014-12-06 14:02:15
什麼字符是字母 - 只是AZ,az? – Scooter 2014-12-06 14:18:25
字符是字母a-z – user3513220 2014-12-06 14:55:19