Created
January 22, 2016 00:47
-
-
Save kishida/12c9846545d11b59052a to your computer and use it in GitHub Desktop.
Simple expression parser that supports add and sub.
This file contains hidden or 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
public class ParseExp { | |
public static void main(String[] args) { | |
int n = 0; | |
String exp = "123+44-21"; | |
int s = 0; | |
int result = 0; | |
char opCh = '+'; | |
for(int i = 0; i < exp.length(); ++i){ | |
char ch = exp.charAt(i); | |
boolean num = ch >= '0' && ch <= '9'; | |
boolean op = ch == '+' || ch == '-'; | |
switch(s){ | |
case 0:// first | |
if(!num){ | |
System.out.printf("error %s on %d%n", ch, i); | |
return; | |
} | |
n = ch - '0'; | |
s = 1; | |
break; | |
case 1:// num | |
if(num){ | |
n = n * 10 + (ch - '0'); | |
} else if (op){ | |
if(opCh == '+'){ | |
result += n; | |
}else if(opCh =='-'){ | |
result -= n; | |
} else { | |
System.out.printf("error %s on %d%n", ch, i); | |
return; | |
} | |
opCh = ch; | |
s = 0; | |
} else { | |
System.out.printf("error %s on %d%n", ch, i); | |
return; | |
} | |
break; | |
} | |
} | |
switch(s){ | |
case 0: | |
System.out.println("error terminated."); | |
return; | |
case 1: | |
if(opCh == '+'){ | |
result += n; | |
}else if(opCh == '-'){ | |
result -= n; | |
} | |
break; | |
} | |
System.out.println(123+44-21); | |
System.out.println(result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment