我正在尝试创建一个读取表达式的标记器。当它获得令牌时,我打印类型和词位,它是运算符的数字。它目前单独打印每个字符,但我需要它一起打印两位数和十进制数。这是我的代码。
public class Tokenizer {
String type;
String lexeme;
/**
* @param args the command line arguments
*/
void getToken(String expression, int i) {
if (expression.charAt(i) == '+')
{
type = "operator";
lexeme = "+";
}
else if (expression.charAt(i) == '-')
{
type = "operator";
lexeme = "-";
}
else if (expression.charAt(i) == '*')
{
type = "operator";
lexeme = "*";
}
else if (expression.charAt(i) == '/')
{
type = "operator";
lexeme = "/";
}
else if (expression.charAt(i) == ' ')
{
; //empty statement. Does nothing if the character is white space
}
else
{
type = "number";
lexeme = Character.toString(expression.charAt(i));
}
}
public static void main(String[] args) {
// TODO code application logic here
String expression = "3+66*2.5";
Tokenizer tokenizer = new Tokenizer();
for (int i = 0; i < expression.length(); i++)
{
tokenizer.getToken(expression, i);
System.out.print("Type: " + tokenizer.type + "\t" + "Lexeme: " + tokenizer.lexeme + "\n");
}
}
}
样本输出 - 实际
Type: number Lexeme: 3
Type: operator Lexeme: +
Type: number Lexeme: 6
Type: number Lexeme: 6
Type: operator Lexeme: *
Type: number Lexeme: 2
Type: number Lexeme: .
Type: number Lexeme: 5
样本输出 - 预期
Type: number Lexeme: 3
Type: operator Lexeme: +
Type: number Lexeme: 66
Type: operator Lexeme: *
Type: number Lexeme: 2.5