Created
August 25, 2017 20:30
-
-
Save adeelibr/53260f91b7add818edb862ddc34a4644 to your computer and use it in GitHub Desktop.
A lexical analyzer made in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This programs works as a lexical analyzer | |
*/ | |
package LexicalAnalyzer2; | |
import java.util.Scanner; | |
/** | |
* @author adeel | |
*/ | |
public class Built { | |
public static void main(String[] args){ | |
System.out.print("State your input: "); | |
Scanner in = new Scanner(System.in); | |
String user_input = in.nextLine(); | |
char array[] = user_input.toCharArray(); /*convert string into character array*/ | |
int size_of_array = array.length; /*Check size of array*/ | |
int count = 0; /*Counter Variable*/ | |
boolean flag = true; /*To identify between spaces and words*/ | |
/*Count number of words including spaces*/ | |
for(int i=0;i<size_of_array;i++){ | |
if(array[i] == ' '){ | |
/*count spaces*/ | |
count++; | |
flag = true; | |
} | |
if(array[i]!=' ' && flag==true){ | |
/*count words*/ | |
count++; | |
flag = false; | |
} | |
}/*End of for loop*/ | |
System.out.println("Number Of Words: " +count); | |
/*Finding total number of keywords in our given string*/ | |
String [] lex = user_input.split(" "); /*split them based on spaces in between*/ | |
size_of_array = lex.length; | |
String [] keywords = new String[6]; /*give the same number in the inner array as well*/ | |
keywords[0] = "if"; | |
keywords[1] = "else"; | |
keywords[2] = "is"; | |
keywords[3] = "throw"; | |
keywords[4] = "then"; | |
keywords[5] = "printf"; | |
keywords[5] = "for" | |
; | |
count = 0; | |
/*Count total number of keywords*/ | |
for(int i=0;i<size_of_array;i++){ | |
for(int j=0;j<6;j++){ | |
if(lex[i].equals(keywords[j])){ | |
count++; | |
break; | |
} | |
}/*end of inner loop*/ | |
}/*end of outer loop*/ | |
System.out.println("Number of keywords: " +count); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment