You are on page 1of 2

Program:

public class LexicalAnalyzer {


static final ArrayList<String> keywordsList = new ArrayList<>(Arrays.asList(
"abstract", "assert", "boolean",
"break", "byte", "case", "catch", "char", "class", "const",
"continue", "default", "do", "double", "else", "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"));

public static void main(String[] args) {


Scanner scan = new Scanner(System.in);
System.out.print("Enter statement: ");
String statement = scan.nextLine();
scan.close();
String temp = "";

ArrayList<String> separator = new ArrayList<>();


ArrayList<String> operator = new ArrayList<>();
ArrayList<String> identifier = new ArrayList<>();
ArrayList<String> keywords= new ArrayList<>();
ArrayList<String> number = new ArrayList<>();
for (int i = 0; i < statement.length(); i++) {
char c = statement.charAt(i);
if (c >= 48 && c < 59) {
temp += Character.toString(c);
if (statement.charAt(i + 1) == ' ') {
i++;
number.add(temp);
temp = "";
} else if (statement.charAt(i + 1) == ';') {
number.add(temp);
i++;
separator.add(";");
temp = "";
}
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
operator.add(Character.toString(c));
} else if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122)) {
temp += Character.toString(c);
if(keywordsList.contains(temp)) {
keywords.add(temp);
temp = "";
}else {
if (statement.charAt(i + 1) == ' ') {
i++;
identifier.add(temp);
temp = "";
} else if (statement.charAt(i + 1) == ';' || statement.charAt(i + 1) == ',') {
identifier.add(temp);
i++;
separator.add(";");
temp = "";
}
}
} else if (c == ';' || c == ',' || c == '(' || c == ')' || c == '{' || c == '}'){
separator.add(Character.toString(c));
}
}
System.out.println("Keywords: " + keywords);
System.out.println("Operator: " + operator);
System.out.println("Separator: " + separator);
System.out.println("Identifier: " + identifier);
System.out.println("Number: " + number);
}
}

Output:

You might also like