如何在多个分数上执行方程

时间:2014-11-04 22:32:39

标签: java math

我已经编写了一些使用两个分数来计算数学表达式的基本代码,但我很难理解如何进行更多的计算。1/2 + 1/2 * 1/2

我的两个分数代码如下。有什么建议吗?

import java.util.Scanner;

public class Evaluate {
    public static void main(String args[]){

        Scanner in = new Scanner(System.in);

        System.out.println("Enter your equation, please seperate fractions and operators with a space: ");

        String[] equation = in.nextLine().split(" ");

        String a = equation[0];
        String a2 = equation[2];
        String a4 = equation[1];

        String[] a1 = a.split("/");
        String[] a3 = a2.split("/");

        int b = Integer.parseInt(a1[0]);
        int c = Integer.parseInt(a1[1]);

        int b1 = Integer.parseInt(a3[0]);
        int c1 = Integer.parseInt(a3[1]);

        Fraction first = new Fraction(b,c);
        Fraction second = new Fraction(b1,c1);

        if(a4.equals("*")){
            Fraction multi = first.multiply(second);
                System.out.println(multi);
        }
        else if(a4.equals("+")){
            Fraction add = first.add(second);
            System.out.println(add);
        }
        else if(a4.equals("-")){
            Fraction sub = first.subtract(second);
            System.out.println(sub);
        }
        else if(a4.equals("/")){
            Fraction div = first.divideBy(second);
            System.out.println(div);
        }



    }
}

2 个答案:

答案 0 :(得分:1)

按空格拆分字符串就足够了,并且可以使用多个运算符:

String[]  equation = in.nextLine.split(" ");

现在你有了这个,你想迭代它并创建两个ArrayLists,一个用于运算符,一个用于表单x/y的分数:

String[] operators = new String[equation.length/2];
String[] fractions = new String[operators.length+1];
for (int i = 0; i < equation.length; i+=2)
{
    fractions[i] = equation[i];
    operators[i] = equation[i+1];
}

现在你有2个ArrayLists包含你需要的所有东西,只需迭代这些:

Fraction[] newFractions = new Fraction[fractions.length];
for (int i = 0; i < fractions.length; i++)
    String[] parts = fractions[i].split("/");
    Fraction[i] = new Fraction(parts[0],parts[1]);

然后遍历运算符ArrayList并执行以下操作:

for (int i = 0; i < operators.length; i++)
{
    if (operators[i] == "*")
        //Multiply your fractions
        //Something like this, I haven't used the Fraction class before, nor heard of it
        //Shouldn't throw out of bounds because the size should be 1 bigger
        newFractions[i+1] = newFractions[i].multiply(newFractions[i+1]);
    else if (operators[i] == "+")
        //Add your fractions
    else if (operators[i] == "-")
        //Subtract your fractions
    else if (operators[i] == "/")
        //Divide your fractions
}

答案 1 :(得分:-1)

您可以使用javascript engine中的java来评估中缀表达式。对于那个导入

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

然后执行以下操作:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String equation = "1/2 + 1/2 * 1/2";
System.out.println(engine.eval(equation));