公式解析 在某些應用中,為了支援靈活性,往往用到自定義的公式。 比如,有如下的原始公式集合:
阿新 • • 發佈:2019-02-12
執行結果:/*公式解析 在某些應用中,為了支援靈活性,往往用到自定義的公式。 比如,有如下的原始公式集合: int add(int x, int y): 返回x與y的和 int add(int x, int y, int z): 返回x,y,z三個數的和 int min(int x, int y): 返回x,y中較小的值 int max(int x, int y): 返回x,y中較大的值 int doubleMe(int x): 返回 x 的2倍 給出一個自定義公式串 add(min(5,3),max(2,8),add(1,doubleMe(1))) 通過手工計算可以得出結果為:14 本題的任務是:編寫一個解析程式,能夠對由上述原始公式任意組合出來的公式計算其結果。 也就是輸入一個自定義公式串,輸出它的計算結果(可以不考慮輸入公式本身有語法錯誤的情況)。 輸入的公式串中可以含有多餘的空格,類似: add( min(5, 3) , max(2 , 8) ) 也是合法的公式。 程式輸入:公式串 程式輸出:該公式的計算值 */ import java.util.Scanner; import java.util.Stack; public class Demo08 { // add 返回x與y的和 public static int add(int x,int y){ return x+y; } // add 返回x,y,z三個數的和 public static int add(int x,int y,int z){ return x+y+z; } // min 返回x,y中較小的值 public static int min(int x, int y){ return x<y?x:y; } // max 返回x,y中較大的值 public static int max(int x, int y){ return x>y?x:y; } // doubleMe 返回 x 的2倍 public static int doubleMe(int x){ return x*2; } public static int check(String s){ Stack<String> method = new Stack<String>(); // 儲存方法名 Stack<Character> bracket = new Stack<Character>();// 儲存對應括號 Stack<String> num = new Stack<String>(); // 儲存數字 Stack<Integer> count = new Stack<Integer>(); //儲存引數個數 StringBuffer ss = new StringBuffer(); // 新增字母 StringBuffer nn = new StringBuffer(); // 新增數字 for(int i=0;i<s.length();i++){ char c = s.charAt(i); if(c>='A'&&c<='Z'||c>='a'&&c<='z'){ ss.append(c); // 拼湊方法名 }else if(c=='('){ method.push(ss.toString()); // 方法名拼湊完成,新增到棧 count.push(0); ss.setLength(0); // 放入方法,並清空臨時串 bracket.push(')'); }else if(c>='0'&&c<='9'){ nn.append(c); // 拼湊數字 }else if(nn.length()!=0){ num.push(nn.toString()); // 數字名拼湊完成,新增到棧 count.push(count.pop()+1); // 引數個數加1 nn.setLength(0); } if(c==')'){ String m = method.pop(); // 得到方法 int[] n = new int[count.pop()]; // 依引數個數開闢陣列 for(int j=0;j<n.length;j++){ // 得到每個引數 n[j] = Integer.parseInt(num.pop()); } bracket.pop(); // 去一層括號 if("add".equals(m)){ if(n.length==2){ // add() 兩個引數 num.push(""+add(n[1],n[0])); }else if(n.length==3){ // add() 三個引數 num.push(""+add(n[2],n[1],n[0])); } }else if("min".equals(m)){ // min() num.push(""+min(n[1],n[0])); }else if("max".equals(m)){ // max() num.push(""+max(n[1],n[0])); }else if("doubleMe".equals(m)){ // doubleMe() num.push(""+doubleMe(n[0])); } if(count.size()!=0){ // 如果不是最外層 count.push(count.pop()+1); } } } return Integer.parseInt(num.pop()); // 返回最後的結果資料 } public static void main(String[] args){ Scanner scan = new Scanner(System.in); System.out.println("輸入公式串"); String s = scan.nextLine(); System.out.println(check(s)); } }
輸入公式串
add(min(5,3),max(2,8),add(1,doubleMe(1)))
14