在java计算器中允许多个输入

时间:2014-07-12 05:17:07

标签: java parsing

我正在使用Eclipse中的小型计算器,用户输入类似1 + 1的等式。但是,我不确定如何允许用户输入更复杂的方程式,如1 + 2 * 3 / 4

此外,如果用户尝试输入的字符串不是有效的等式,我希望出现错误。这是我的代码:

public static double addition(double x, double y) // The Addition Operation
{
    double add = x + y;
    return add;
}

public static double subtraction(double x, double y) // The Subtraction Operation
{
    double sub = x - y;
    return sub;
}

public static double division(double x, double y) // The Devision Operation
{
    double div = x / y;
    return div;
}

public static double multiplication(double x, double y) // The Multiplication Operation
{
    double multi = x * y;
    return multi;
}

public static double factorial(double x) // The Factorial (F!)
{ 
    double result = 1;
    while (x > 1)
    {
        result = result * x;
        x = x - 1;
    }
    return result;
}

static Scanner scanner = new Scanner(System.in); // a Global Scanner.

public static void main(String[] args)
{
    double numb1, numb2;
    char operation;
    System.out.println("Enter Your Equation: ");

    // Split string by space
    String[] parts = scanner.nextLine().split("");

    // Convert to corresponding types
    operation = parts[1].charAt(0);

    switch (operation)
    {
        case '+':
            numb1 = Integer.parseInt(parts[0]);
            operation = parts[1].charAt(0);
            numb2 = Integer.parseInt(parts[2]);
            System.out.println("The Product is: " + addition(numb1, numb2));
            break;

        case '-':
            numb1 = Integer.parseInt(parts[0]);
            operation = parts[1].charAt(0);
            numb2 = Integer.parseInt(parts[2]);
            System.out.println("The Product is: " + subtraction(numb1, numb2));
            break;
        case '*':
            numb1 = Integer.parseInt(parts[0]);
            operation = parts[1].charAt(0);
            numb2 = Integer.parseInt(parts[2]);
            System.out.println("The Product is: " + multiplication(numb1, numb2));
            break;
        case '/':
            numb1 = Integer.parseInt(parts[0]);
            operation = parts[1].charAt(0);
            numb2 = Integer.parseInt(parts[2]);
            System.out.println("The Product is: " + division(numb1, numb2));
            break;
        case '!':
            numb1 = Integer.parseInt(parts[0]);
            operation = parts[1].charAt(0);
            System.out.println("The Product is: " + factorial(numb1));
    }
}

1 个答案:

答案 0 :(得分:5)

有一些简单的方法可以在Java中评估表达式,但假设这是出于学习目的:

解析数学方程中最棘手的部分是考虑操作的顺序 - 也就是说,你不能只是遍历方程并逐位计算(类似3 + 2 * 5之类的东西会失败这种情况)。

您正在寻找的是解析中缀表达式的方法;关于该主题的here部分将向您介绍您必须做的基本想法。那里没有Java代码,但这会带来乐趣,对吧?