1importjava.util.Scanner;23classMain{4publicstaticvoidmain(String[] args){5System.out.println("数式を入力してください");6Scanner scanner =newScanner(System.in);7String formula = scanner.nextLine();8Expr e =newExpr(formula);9int val = e.syn();10if(e.tok !=0)System.out.println("syntax error");11elseSystem.out.println(val);12}13}1415classExpr{// 数式クラス (expression)16String str;int len, pos, val;char tok;1718Expr(String s){ str = s; len = s.length(); pos =0;}1920charlex(){// 字句解析 (lexical analyzer)21while(pos < len)22if((tok = str.charAt(pos++))>='0'&& tok<='9'){23for(val = tok -'0'; pos < len &&24(tok = str.charAt(pos))>='0'&& tok<='9'; pos++)25 val = val *10+(tok -'0');26return tok ='0';27}28elseif(tok !=' ')return tok;29return tok =0;// end of string30}3132intsyn(){// 構文解析 (syntax analyzer)33int v =0;34for(char op ='+';lex()!=0;)35if(tok =='0')36switch(op){37case'+': v += val;break;38case'-': v -= val;break;39case'*': v *= val;break;40case'/': v /= val;break;41default:return v;42}43else op = tok;44return v;45}46}
追記
演算子の優先順位と括弧の処理も追加した構文解析です。
Java
1importjava.util.Scanner;23classMain{4publicstaticvoidmain(String[] args){5System.out.println("数式を入力してください");6Scanner scanner =newScanner(System.in);7String formula = scanner.nextLine();8Expr e =newExpr(formula);9int val = e.syn(0);10if(e.tok !=0)System.out.println("syntax error");11elseSystem.out.println(val);12}13}1415classExpr{// 数式クラス (expression)16String str;int len, pos, val;char tok;1718Expr(String s){ str = s; len = s.length(); pos =0;}1920charlex(){// 字句解析 (lexical analyzer)21while(pos < len)22if((tok = str.charAt(pos++))>='0'&& tok<='9'){23for(val = tok -'0'; pos < len &&24(tok = str.charAt(pos))>='0'&& tok<='9'; pos++)25 val = val *10+(tok -'0');26return tok ='0';27}28elseif(tok !=' ')return tok;29return tok =0;// end of string30}3132finalstaticchar[] op ={'+','-','*','/'};3334intsyn(int i){// 構文解析 (syntax analyzer)35int v;36if(i <4)37for(v =syn(i+2); tok == op[i]|| tok == op[i+1];)38if(tok =='+') v +=syn(i+2);39elseif(tok =='-') v -=syn(i+2);40elseif(tok =='*') v *=syn(i+2);41else v /=syn(i+2);42elseif(lex()=='0'){ v = val;lex();}43elseif(tok =='('){44 v =syn(0);45if(tok ==')')lex();46else tok =1;47}48else v = tok =1;49return v;50}51}