20175316盛茂淞 2018-2019-2《Java程序设计》结对编程项目-四则运算 第一周 阶段性总结

20175316盛茂淞 2018-2019-2《Java程序设计》结对编程项目-四则运算 第一周 阶段性总结

需求分析

  • 自动生成四则运算题目(加、减、乘、除)。
  • 既可以用前缀算法(波兰算法)实现加减乘除也可以用后缀算法实现。
  • 支持复合运算。

设计思路

  • 首先我们先实现前缀表达式的方法,通过阅读材料大致了解到如下方法:
  • 前缀表达式的计算机求值:
    从右至左扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(栈顶元素 op 次顶元素),并将结果入栈;重复上述过程直到表达式最左端,最后运算得出的值即为表达式的结果。
    例如前缀表达式“- × + 3 4 5 6”:

(1) 从右至左扫描,将6、5、4、3压入堆栈;

(2) 遇到+运算符,因此弹出3和4(3为栈顶元素,4为次顶元素,注意与后缀表达式做比较),计算出3+4的值,得7,再将7入栈;

(3) 接下来是×运算符,因此弹出7和5,计算出7×5=35,将35入栈;

(4) 最后是-运算符,计算出35-6的值,即29,由此得出最终结果。
可以看出,用计算机计算前缀表达式的值是很容易的。

  • 随后后缀表达式实现方法上与前缀有异同之处:
  • 后缀表达式的计算机求值:
    与前缀表达式类似,只是顺序是从左至右:
    从左至右扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(次顶元素 op 栈顶元素),并将结果入栈;重复上述过程直到表达式最右端,最后运算得出的值即为表达式的结果。
    例如后缀表达式“3 4 + 5 × 6 -”:

(1) 从左至右扫描,将3和4压入堆栈;

(2) 遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素,注意与前缀表达式做比较),计算出3+4的值,得7,再将7入栈;

(3) 将5入栈;

(4) 接下来是×运算符,因此弹出5和7,计算出7×5=35,将35入栈;

(5) 将6入栈;

(6) 最后是-运算符,计算出35-6的值,即29,由此得出最终结果。

代码

import java.util.Scanner;
import java.util.Stack;
public class sizeyunsuan {
    public static final String USAGE = "== usage ==\n"
            + "input the expressions, and then the program "
            + "will calculate them and show the result.\n"
            + "input 'bye' to exit.\n";
    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(USAGE);
        Scanner scanner = new Scanner(System.in);
        String input = "";
        final String CLOSE_MARK = "bye";
        System.out.println("input an expression:");
        input = scanner.nextLine();
        while (input.length() != 0
                && !CLOSE_MARK.equals((input))) {
            System.out.print("Polish Notation (PN):");
            try {
                toPolishNotation(input);
            } catch (NumberFormatException e) {
                System.out.println("\ninput error, not a number.");
            } catch (IllegalArgumentException e) {
                System.out.println("\ninput error:" + e.getMessage());
            } catch (Exception e) {
                System.out.println("\ninput error, invalid expression.");
            }
            System.out.print("Reverse Polish Notation (RPN):");
            try {
                toReversePolishNotation(input);
            } catch (NumberFormatException e) {
                System.out.println("\ninput error, not a number.");
            } catch (IllegalArgumentException e) {
                System.out.println("\ninput error:" + e.getMessage());
            } catch (Exception e) {
                System.out.println("\ninput error, invalid expression.");
            }
            System.out.println("input a new expression:");
            input = scanner.nextLine();
        }
        System.out.println("program exits");
    }
    /**
     * parse the expression , and calculate it.
     * @param input
     * @throws IllegalArgumentException
     * @throws NumberFormatException
     */
    private static void toPolishNotation(String input)
            throws IllegalArgumentException, NumberFormatException {
        int len = input.length();
        char c, tempChar;
        Stack<Character> s1 = new Stack<Character>();
        Stack<Double> s2 = new Stack<Double>();
        Stack<Object> expression = new Stack<Object>();
        double number;
        int lastIndex = -1;
        for (int i=len-1; i>=0; --i) {
            c = input.charAt(i);
            if (Character.isDigit(c)) {
                lastIndex = readDoubleReverse(input, i);
                number = Double.parseDouble(input.substring(lastIndex, i+1));
                s2.push(number);
                i = lastIndex;
                if ((int) number == number)
                    expression.push((int) number);
                else
                    expression.push(number);
            } else if (isOperator(c)) {
                while (!s1.isEmpty()
                        && s1.peek() != ')'
                        && priorityCompare(c, s1.peek()) < 0) {
                    expression.push(s1.peek());
                    s2.push(calc(s2.pop(), s2.pop(), s1.pop()));
                }
                s1.push(c);
            } else if (c == ')') {
                s1.push(c);
            } else if (c == '(') {
                while ((tempChar=s1.pop()) != ')') {
                    expression.push(tempChar);
                    s2.push(calc(s2.pop(), s2.pop(), tempChar));
                    if (s1.isEmpty()) {
                        throw new IllegalArgumentException(
                                "bracket dosen't match, missing right bracket ')'.");
                    }
                }
            } else if (c == ' ') {
                // ignore
            } else {
                throw new IllegalArgumentException(
                        "wrong character '" + c + "'");
            }
        }
        while (!s1.isEmpty()) {
            tempChar = s1.pop();
            expression.push(tempChar);
            s2.push(calc(s2.pop(), s2.pop(), tempChar));
        }
        while (!expression.isEmpty()) {
            System.out.print(expression.pop() + " ");
        }
        double result = s2.pop();
        if (!s2.isEmpty())
            throw new IllegalArgumentException("input is a wrong expression.");
        System.out.println();
        if ((int) result == result)
            System.out.println("the result is " + (int) result);
        else
            System.out.println("the result is " + result);
    }
    /**
     * parse the expression, and calculate it.
     * @param input
     * @throws IllegalArgumentException
     * @throws NumberFormatException
     */
    private static void toReversePolishNotation(String input)
            throws IllegalArgumentException, NumberFormatException {
        int len = input.length();
        char c, tempChar;
        Stack<Character> s1 = new Stack<Character>();
        Stack<Double> s2 = new Stack<Double>();
        double number;
        int lastIndex = -1;
        for (int i=0; i<len; ++i) {
            c = input.charAt(i);
            if (Character.isDigit(c) || c == '.') {
                lastIndex = readDouble(input, i);
                number = Double.parseDouble(input.substring(i, lastIndex));
                s2.push(number);
                i = lastIndex - 1;
                if ((int) number == number)
                    System.out.print((int) number + " ");
                else
                    System.out.print(number + " ");
            } else if (isOperator(c)) {
                while (!s1.isEmpty()
                        && s1.peek() != '('
                        && priorityCompare(c, s1.peek()) <= 0) {
                    System.out.print(s1.peek() + " ");
                    double num1 = s2.pop();
                    double num2 = s2.pop();
                    s2.push(calc(num2, num1, s1.pop()));
                }
                s1.push(c);
            } else if (c == '(') {
                s1.push(c);
            } else if (c == ')') {
                while ((tempChar=s1.pop()) != '(') {
                    System.out.print(tempChar + " ");
                    double num1 = s2.pop();
                    double num2 = s2.pop();
                    s2.push(calc(num2, num1, tempChar));
                    if (s1.isEmpty()) {
                        throw new IllegalArgumentException(
                                "bracket dosen't match, missing left bracket '('.");
                    }
                }
            } else if (c == ' ') {
                // ignore
            } else {
                throw new IllegalArgumentException(
                        "wrong character '" + c + "'");
            }
        }
        while (!s1.isEmpty()) {
            tempChar = s1.pop();
            System.out.print(tempChar + " ");
            double num1 = s2.pop();
            double num2 = s2.pop();
            s2.push(calc(num2, num1, tempChar));
        }
        double result = s2.pop();
        if (!s2.isEmpty())
            throw new IllegalArgumentException("input is a wrong expression.");
        System.out.println();
        if ((int) result == result)
            System.out.println("the result is " + (int) result);
        else
            System.out.println("the result is " + result);
    }
    /**
     * calculate the two number with the operation.
     * @param num1
     * @param num2
     * @param op
     * @return
     * @throws IllegalArgumentException
     */
    private static double calc(double num1, double num2, char op)
            throws IllegalArgumentException {
        switch (op) {
            case '+':
                return num1 + num2;
            case '-':
                return num1 - num2;
            case '*':
                return num1 * num2;
            case '/':
                if (num2 == 0) throw new IllegalArgumentException("divisor can't be 0.");
                return num1 / num2;
            default:
                return 0; // will never catch up here
        }
    }
    /**
     * compare the two operations' priority.
     * @param c
     * @param peek
     * @return
     */
    private static int priorityCompare(char op1, char op2) {
        switch (op1) {
            case '+': case '-':
                return (op2 == '*' || op2 == '/' ? -1 : 0);
            case '*': case '/':
                return (op2 == '+' || op2 == '-' ? 1 : 0);
        }
        return 1;
    }
    /**
     * read the next number (reverse)
     * @param input
     * @param start
     * @return
     * @throws IllegalArgumentException
     */
    private static int readDoubleReverse(String input, int start)
            throws IllegalArgumentException {
        int dotIndex = -1;
        char c;
        for (int i=start; i>=0; --i) {
            c = input.charAt(i);
            if (c == '.') {
                if (dotIndex != -1)
                    throw new IllegalArgumentException(
                            "there have more than 1 dots in the number.");
                else
                    dotIndex = i;
            } else if (!Character.isDigit(c)) {
                return i + 1;
            } else if (i == 0) {
                return 0;
            }
        }
        throw new IllegalArgumentException("not a number.");
    }

    /**
     * read the next number
     * @param input
     * @param start
     * @return
     * @throws IllegalArgumentException
     */
    private static int readDouble(String input, int start)
            throws IllegalArgumentException {
        int len = input.length();
        int dotIndex = -1;
        char c;
        for (int i=start; i<len; ++i) {
            c = input.charAt(i);
            if (c == '.') {
                if (dotIndex != -1)
                    throw new IllegalArgumentException(
                            "there have more than 1 dots in the number.");
                else if (i == len - 1)
                    throw new IllegalArgumentException(
                            "not a number, dot can't be the last part of a number.");
                else
                    dotIndex = i;
            } else if (!Character.isDigit(c)) {
                if (dotIndex == -1 || i - dotIndex > 1)
                    return i;
                else
                    throw new IllegalArgumentException(
                            "not a number, dot can't be the last part of a number.");
            } else if (i == len - 1) {
                return len;
            }
        }

        throw new IllegalArgumentException("not a number.");
    }
    /**
     * return true if the character is an operator.
     * @param c
     * @return
     */
    private static boolean isOperator(char c) {
        return (c=='+' || c=='-' || c=='*' || c=='/');
    }
}

测试说明

  • 正常测试输入图片说明
  • 异常测试
  • 边界测试输入图片说明

码云链接

[码云连接]https://gitee.com/shengmaosong/java-besti-20175316/blob/master/jiedui/jiedui1/sizeyunsuan.java

UML图

输入图片说明

## 参考资料

结对学习照片

猜你喜欢

转载自www.cnblogs.com/sms369/p/10654257.html