简单的Java计算器来解决表达式

时间:2015-05-21 01:20:24

标签: java loops arraylist switch-statement calculator

我正在研究解决表达式的计算器。我试图弄清楚如何以PEMDAS顺序计算它。我有一个for循环来遍历数组列表和一个调用一个进行数学运算的类的开关。我已经尝试过如果声明,但是还没有能够解决这个问题。

如何更改此项以确保以正确的顺序解决表达式?这就是我到目前为止所拥有的:

/*
Peter Harmazinski
Simple Calculator

This program solves expressions
*/

import java.util.*;

public class SimpleCalculator2 {
    static SimpleMath math = new SimpleMath();

    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        boolean again = true;
        double number1 = 0.0;
        double number2 = 0.0;
        double answer = 0.0;
        double results = 0.0;
        String delims = "[ ]+";

        getIntroduction();

        while (again) {
            System.out.println("Please enter your expression.");
            String input = console.nextLine();
            System.out.println("This is the user's input: " + input);

            //Parses string into array list
            List<String> list = new ArrayList<String>(Arrays.asList(input.split(delims)));
            System.out.println("list: " + list);

            results = doMath(list, number1, number2);
            getResults(results);
        }
        console.close();
    }

    public static void getIntroduction() {
        System.out.println("This is a simple calculator that solves expressions.");
    }

    //Traverses array list to identify operators and does math for surrounding numbers
    //then answer is inserted in i-1 element and the elements i and i+1 are deleted

    public static double doMath(List<String> list, double number1, double number2) {
        double answer = 0.0;
        double results = 0.0;
        while (list.size() > 1) {
            for (int i = 0; i < list.size(); i++) {
                    switch (list.get(i)) {
                        case "*" :
                            number1 = Double.parseDouble(list.get(i - 1));
                            number2 = Double.parseDouble(list.get(i + 1));
                            answer = math.multiply(number1, number2);
                            System.out.println(answer);
                            list.add(i - 1, Double.toString(answer));
                            list.subList(i, i + 3).clear();
                            System.out.println(list);
                            break;
                        case "/" :
                            number1 = Double.parseDouble(list.get(i - 1));
                            number2 = Double.parseDouble(list.get(i + 1));
                            answer = math.divide(number1, number2);
                            System.out.println(answer);
                            list.add(i - 1, Double.toString(answer));
                            list.subList(i, i + 3).clear();
                            System.out.println(list);
                            break;
                        case "+" :
                            number1 = Double.parseDouble(list.get(i - 1));
                            number2 = Double.parseDouble(list.get(i + 1));
                            answer = math.add(number1, number2);
                            System.out.println(answer);
                            list.add(i - 1, Double.toString(answer));
                            list.subList(i, i + 3).clear();
                            System.out.println(list);
                            break;
                        case "-" :
                            number1 = Double.parseDouble(list.get(i - 1));
                            number2 = Double.parseDouble(list.get(i + 1));
                            answer = math.subtract(number1, number2);
                            System.out.println(answer);
                            list.add(i - 1, Double.toString(answer));
                            list.subList(i, i + 3).clear();
                            System.out.println(list);
                            break;
                        }
                }   
            }   
        return answer;
    }

    public static void getResults(double results) {
        System.out.println("Results are: " + results);
    }
}

3 个答案:

答案 0 :(得分:1)

我认为实现这一目标的一个非常标准的算法是Dijkstra的Shunting Yard算法,然后是后缀评估。你可以在这里阅读它,伪代码在这里,但你可能需要对基本数据结构有一些了解:http://en.wikipedia.org/wiki/Shunting-yard_algorithm

如果您不了解堆栈,队列和后缀表示法,您可以编写一个更慢,更简单但更混乱的实现。我曾经尝试过sin,cos,trig,log这一次,并且代码变得有用,但不是我会再试一次。

基本上,我们的想法是只用1个运算符找到最高优先级的表达式,对其进行求值,并用它替换它。这是一些伪代码:

input = [user input]
while expression still contains (, ), +, -, *, or /:
    toEvaluate = highest priority expression with 1 operator (e.g. 1+2, or 2*3)
    calculate the decimal value of toEvaluate
    modify input so that you replace toEvaluate with its decimal value

请注意,在doMath()实施中,在for循环中,您只需在看到所有运算符后立即对其进行评估。例如,考虑

1 + 2 * 3

您将看到+首先计算1 + 2,然后将该结果乘以3.相反,您需要首先浏览整个列表,找到最高优先级的运算符,对其进行评估,然后再从头开始。

答案 1 :(得分:-1)

因为你将它输入一个字符串中,为什么不创建一个迭代遍历每个字符的for循环呢?

// This for loop will get you the string with only one operator in it.
// EX: 30+32
// You will have to find some way to compute this string.
for(int i = 0; i < userInput.length(); i++)
{
   //int a will be the INDEX of the first operator
   //int b will be the INDEX of the place where a new operator comes up 
   char c = userInput.getCharAt(i);
   a = 0;
   //I'm just gonna do it with + and - for now. Add any other operators.
   if(c == '+' || c == '-')
   {
       b = i;
       String stringToCompute = userInput.substring(a,b);
       //Find some way to take the string there then compute it. 
       //Maybe another for loop with stringToCompute to find where the
       // operator is and then add/subtract the two doubles.  

       // Now reset it 
       a = i;
       b = null;
   }
}

答案 2 :(得分:-1)

以下是一些可能解决此问题的设计:

  1. 您可以将处理分为两部分:解析和评估。在解析阶段,您将字符串转换为表示如何评估它的数据结构。在评估阶段,您遍历树并评估表达式。

  2. 您可以通过运算符拆分列表以评估最后一个(加号和减号),评估每个段(时间和除法)。如果设计得当,这可能是递归的。

  3. 第一个选项更好,因为它更具可扩展性,但实现起来也更加努力。以下是通过解析和评估生成的示例数据结构:

    interface Term {
        double getValue();
    }
    
    enum Operator {
        MULTIPLY, DIVIDE, ADD, SUBTRACT;
        double getValue(List<Double> operands) {
            ...
        }
    }
    
    class Operation implements Term {
        List<Term> operands;
        Operator operator;
        double getValue() {
            return operator.getValue(operands);
        }
    }
    
    class Constant implements Term {
        private final double value;
        double getValue() {
            return value;
        }
    }