軟件體系結構的第二次實驗(解釋器風格與管道過濾器風格
阿新 • • 發佈:2017-10-28
out calc images 編譯 而不是 模型 ima ann n)
一、實驗目的
1.熟悉體系結構的風格的概念
2.理解和應用管道過濾器型的風格。
3、理解解釋器的原理
4、理解編譯器模型
二、實驗環境
硬件:
軟件:Python或任何一種自己喜歡的語言
三、實驗內容
1、實現“四則運算”的簡易翻譯器。
結果要求:
1)實現加減乘除四則運算,允許同時又多個操作數,如:2+3*5-6 結果是11
2)被操作數為整數,整數可以有多位
3)處理空格
4)輸入錯誤顯示錯誤提示,並返回命令狀態“CALC”
圖1 實驗結果示例
加強練習:
1、有能力的同學,可以嘗試實現賦值語句,例如x=2+3*5-6,返回x=11。(註意:要實現解釋器的功能,而不是只是顯示)
2、嘗試實現自增和自減符號,例如x++
2、采用管道-過濾器(Pipes and Filters)風格實現解釋器
圖2 管道-過濾器風格
圖 3 編譯器模型示意圖
本實驗,實現的是詞法分析和語法分析兩個部分。
四、實驗步驟:
源代碼:
import java.util.*; public class Test { public static void main(String[] args) { while(true){ Scanner scanner= new Scanner(System.in); System.out.print("calc > "); String text = scanner.nextLine(); if (analyzer(text)) System.out.println(calculate(toSuffix(text))); else System.out.println("輸入有誤,請重新輸入!!"); } }//驗證是否有空格 static List<Object> toSuffix(String s) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("+", 0); map.put("-", 0); map.put("*", 1); map.put("/", 1); List<Object> list = new ArrayList<Object>(); s = s.replace(" ", ""); String[] number = s.split("[^\\d]"); String[] operator = s.split("\\d+"); Stack<String> stack = new Stack<String>(); for (int i = 0; i < number.length; i++) { if (operator[i].length() != 0) { while (!stack.isEmpty() && map.get(operator[i]) <= map.get(stack.peek())) { list.add(stack.pop()); } stack.push(operator[i]); } list.add(Double.parseDouble(number[i])); } while (!stack.isEmpty()) { list.add(stack.pop()); } return list; } //計算 static double calculate(List<Object> list) { Stack<Double> stack = new Stack<Double>(); for (Object obj : list) { if (obj instanceof Double) { stack.push((Double) obj); } else { double b = stack.pop(); double a = stack.pop(); if (obj.equals("+")) stack.push(a + b); if (obj.equals("-")) stack.push(a - b); if (obj.equals("*")) stack.push(a * b); if (obj.equals("/")) stack.push(a / b); } } return stack.pop(); } private static boolean analyzer(String text) { String[] signs = {"+", "-", "*", "/"}; boolean isRight = true; //語法分析 boolean haveSign = false; for (String sign : signs) { //是否包含運算符 if (text.contains(sign)) { haveSign = true; } //是否有連續的運算符 if (text.contains(sign + sign)) { isRight = false; } //首尾是否為運算符 if ( text.indexOf(sign) == 0 || text.lastIndexOf(sign) == text.length() - 1) { isRight = false; } } isRight = isRight && haveSign; return isRight; } }
實驗結果 :
結構圖:
軟件體系結構的第二次實驗(解釋器風格與管道過濾器風格