Last active
January 23, 2016 11:39
-
-
Save kishida/a96699f1769300b154cd to your computer and use it in GitHub Desktop.
Simple expression parser that supports add and sub and mul.
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 MulParseExp { | |
public static void main(String[] args) { | |
int n = 0; | |
String exp = "123+44*2-21"; | |
int s = 0; | |
int result = 0; | |
char opCh = '+'; | |
int mulNum = 1; | |
for(int i = 0; i < exp.length(); ++i){ | |
char ch = exp.charAt(i); | |
boolean num = ch >= '0' && ch <= '9'; | |
boolean op = ch == '+' || 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){ | |
mulNum *= n; | |
if(ch == '*'){ | |
//mul = true; | |
}else{ | |
if(opCh == '+'){ | |
result += mulNum; | |
}else if(opCh =='-'){ | |
result -= mulNum; | |
} else { | |
System.out.printf("error %s on %d%n", ch, i); | |
return; | |
} | |
opCh = ch; | |
mulNum = 1; | |
} | |
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: | |
mulNum *= n; | |
if(opCh == '+'){ | |
result += mulNum; | |
}else if(opCh == '-'){ | |
result -= mulNum; | |
} | |
break; | |
} | |
System.out.println(123+44*2-21); | |
System.out.println(result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment