创建一个GUI,允许用户输入前缀表达式并在GUI中显示结果

时间:2015-04-06 01:51:34

标签: java user-interface

import java.util.*;

public class PrefixExpression
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("This program evaluates prefix expressions ");
        System.out.println("for operators *, /, %, +, and - ");
        System.out.print("expression? ");
        System.out.println("value = " + evaluate(keyboard));
    }

    // pre : input contains a legal prefix expression
    // post: expression is consumed and the result is returned
    public static double evaluate(Scanner input)
    {
        if (input.hasNextDouble())
        {
            return input.nextDouble();
        }
        else
        {
            String operator = input.next();
            double operand1 = evaluate(input);
            double operand2 = evaluate(input);
            return evaluate(operator, operand1, operand2);
        }
    }

    // pre : operator is one of *, /, %, + or -
    // post: returns the result of applying the given operator to
    //       the given operands
    public static double evaluate(String operator, double operand1, double operand2)
    {
        if (operator.equals("*"))
        {
            return operand1 * operand2;
        }
        else if (operator.equals("/"))
        {
            return operand1 / operand2;
        }
        else if (operator.equals("%"))
        {
            return operand1 % operand2;
        }
        else if (operator.equals("+"))
        {
            return operand1 + operand2;
        }
        else if (operator.equals("-"))
        {
            return operand1 - operand2;
        }
        else
        {
            throw new RuntimeException("illegal operator " + operator);
        }
    }
}

我需要帮助为此前缀表达式程序创建GUI。 GUI允许用户输入前缀表达式,结果显示在GUI中。

示例:

输入表达式:* + 16 4 + 3 1

结果:80

感谢您的帮助。

0 个答案:

没有答案