Skip to content
Snippets Groups Projects
Commit 42f8c59a authored by Dominic Daniel Krämer's avatar Dominic Daniel Krämer
Browse files

implemented lexter in Lexter.java and fitting tests in Application.java

parent 9116a7b1
No related branches found
No related tags found
1 merge request!2Dominicsbranch
public class Application {
import java.util.Arrays;
import java.util.List;
public class Application {
public static void main(String[] args) {
List<String> test = Arrays.asList("1 + x^2 - (31 * x)");
for (String value: test) {
List<Lexer.Token> tokens = Lexer.lex(value);
for(Lexer.Token singleToken: tokens) {
System.out.println(singleToken.toString());
}
}
}
}
import java.util.LinkedList;
import java.util.List;
public class Lexer {
public static enum TokenType {
NUMBER, VARIABLE, SPECIAL
}
public static class Token {
protected TokenType type;
protected String data;
public Token(TokenType type, String data) {
this.type = type;
this.data = data;
}
public TokenType getType() {
return type;
}
public String getData() {
return data;
}
@Override
public String toString() {
return String.format("type: %s, data: %s", type, data);
}
}
public static List<Token> lex(String input) {
List<Token> result = new LinkedList<Token>();
for(int index=0; index < input.length();) {
char current = input.charAt(index);
if(Character.isDigit(current)) {
int endIndex = index+1;
if(endIndex<input.length()) {
while(Character.isDigit(input.charAt(endIndex)) && endIndex<input.length()) {
endIndex += 1;
}
}
Token token = new Token(TokenType.NUMBER, input.substring(index,endIndex));
result.add(token);
index += endIndex - index;
}
else if(Character.isWhitespace(current)) {
index++;
}
else if(Character.isLetter(current)){
int endIndex = index+1;
if(endIndex<input.length()) {
while(Character.isLetter(input.charAt(endIndex)) && endIndex<input.length()) {
endIndex += 1;
}
}
Token token = new Token(TokenType.VARIABLE, input.substring(index,endIndex));
result.add(token);
index += endIndex - index;
}
else {
Token token = new Token(TokenType.SPECIAL, String.valueOf(current));
result.add(token);
index++;
}
}
return result;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment