首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java:只从左到右计算数学表达式

Java:只从左到右计算数学表达式
EN

Stack Overflow用户
提问于 2011-07-12 14:51:51
回答 5查看 2.6K关注 0票数 0

我编写了一个Java程序,它从左到右计算一个数学表达式(没有优先级,只是从左到右)。但是,我没有得到想要的输出。

代码语言:javascript
运行
复制
import java.util.*;      
public class Evaluation {              
    //private static final char[] validOperators = {'/','*','+','-'};      
    private Evaluation() 
    {
        /* Using a private contructor to prevent instantiation
           Using class as a simple static utility class
         */
    }

    private static int evaluate(String leftSide, char oper, String rightSide)
            throws IllegalArgumentException
    {
        System.out.println("Evaluating: " + leftSide +  " (" + oper + ") " + rightSide);
        int total = 0;
        int leftResult = 0;
        int rightResult = 0;
        String originalString =leftSide;
        int operatorLoc  = findOperatorLocation(leftSide);
        leftSide = leftSide.substring(0,operatorLoc);
        rightSide = originalString.substring(operatorLoc+1,operatorLoc+2);
        String remainingString = originalString.substring(operatorLoc+2,originalString.length());

        System.out.println("leftSide -->"+leftSide);
        System.out.println("rightSide -->"+rightSide);
        System.out.println("remainingString --->"+remainingString);

        try {
            leftResult = Integer.parseInt(leftSide);
        } catch(Exception e) {
            throw new IllegalArgumentException(
                "Invalid value found in portion of equation: "
                + leftSide);
        }

        try {
            rightResult = Integer.parseInt(rightSide);
        } catch(Exception e) {
            throw new IllegalArgumentException(
                "Invalid value found in portion of equation: "
                + rightSide);
        }

        System.out.println("Getting result of: " + leftResult + " " + oper + " " + rightResult);
        switch(oper)
        {
        case '/':
            total = leftResult / rightResult; break;
        case '*':
            total = leftResult * rightResult; break;
        case '+':
            total = leftResult + rightResult; break;
        case '-':
            total = leftResult - rightResult; break;
        default:
            throw new IllegalArgumentException("Unknown operator.");
        }

        System.out.println("Returning a result of: " + total);
        String totally = String.valueOf(total)+remainingString;
        return evaluate(totally,findCharacter(totally),remainingString);
    }

    private static int findOperatorLocation(String string) {
        int index = -1;         
        index = string.indexOf(string.substring(1,2));
        if(index >= 0) {
            return index;
        }
        return index;
    }

    private static char findCharacter(String string) {
        char c='\u0000';  
        int index = -1;         
        index = string.indexOf(string.substring(1,2));
        if(index >= 0){             
            c = string.charAt(index);
            return c;
        }                       
        return c;   
    }

    public static int processEquation(String equation)
        throws IllegalArgumentException
    {
        return evaluate(equation,'+',"0");
    }

    public static void main(String[] args)
    {
        //String usage = "Usage: java MathParser equation\nWhere equation is a series"
        // + " of integers separated by valid operators (+,-,/,*)";

        //if(args.length < 1 || args[0].length() == 0)
        // System.out.println(usage);
        Scanner input = new Scanner(System.in); 
        System.out.print("Enter the equation to be evaluated ");

        String equation = (String)input.next();
        int result = Evaluation.processEquation(equation);
        System.out.println("The result of your equation ("
            + equation + ") is: " + result);

        //catch(IllegalArgumentException iae)
        //{
        //  System.out.println(iae.getMessage() + "\n" + usage);
        //}
    }
}

下面是我正在尝试使用的输入,以及我所期望的:

3+5*2-5

=>8*2-5

=>16-5

=>Expected输出:11

但是我得到了这个输出:

输入要求3+5*2-5的方程

评价: 3+5*2-5 (+) 0

leftSide -->3

rightSide -->5

remainingString ->*2-5

结果:3+5

返回结果:8

评价: 8*2-5 (*) *2-5

leftSide -->8

rightSide -->2

remainingString ->-5

成绩:8*2

返回结果: 16

评价: 16-5 (6) -5

leftSide -->1

rightSide -->-

remainingString ->5

线程“主”java.lang.IllegalArgumentException中的异常:在等式的部分中找到的无效值:-

在Evaluation.evaluate(Evaluation.java:49)

在Evaluation.evaluate(Evaluation.java:70)

在Evaluation.evaluate(Evaluation.java:70)

在Evaluation.processEquation(Evaluation.java:98)

在Evaluation.main(Evaluation.java:112)

我无法使我的程序通用于任何输入的方程式。

我很感激你能提供的任何帮助。

请注意,这不是家庭作业问题。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-07-12 14:58:53

您的findOperatorLoc不正确。

它自动假定运算符是第二个字符。

代码语言:javascript
运行
复制
index = string.indexOf(string.substring(1,2));

编辑--一个更干净的实现可能是这样的。根据运算符将方程拆分,然后根据操作数拆分方程。您将得到两个数组,一个包含所有操作符,另一个包含所有操作数。

代码语言:javascript
运行
复制
            String[] aa = op.split("[*+-]");
            for ( String s : aa )
                    System.out.println(s);
            String[] bb = op.split("[0-9]");
            for ( String s : bb )
                    System.out.println(s);

            // Now loop through the operand array and apply the necessary oeprator in order
            for ( int i = 0 ; i < aa.length ; i++ ) {
                      int val = applyOperator(Integer.parseInt(aa[i]), Integer.parseInt(aa[i+1]), bb[i]);
            }

这只是伪码..。我将留给您实现applyOperator方法。

票数 1
EN

Stack Overflow用户

发布于 2011-07-12 14:59:36

您将得到此错误,因为rightSide具有"-“字符串值,并且试图对其执行Integer.parseInt()操作。

票数 1
EN

Stack Overflow用户

发布于 2011-07-12 15:00:43

确定rightSide的代码以及findOperatorLocation方法都假设所有数字和中间结果只有一个数字。所以,当你有一个中间结果(16)有两位数时,你就会遇到问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6666169

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档