1

我想知道他们是否可以在文本字段中输入诸如“5 * 5”之类的内容。

然后在输入时,文档将获取数据库并能够返回 25。

我很困惑,因为您输入到文本字段的内容必须是 aString并且当您使用Number()转换器时系统会感到困惑。

4

2 回答 2

1

您需要在操作符处拆分字符串(使用正则表达式),然后保留这些操作符。

我自己没有耐心做这件事,但你也需要优先考虑某些操作(先乘法再加法等)。

我已经编写了一些代码来帮助您入门 - 请注意,它仅适用于当前形式的非常简单的算法:

// Finds +, - and *.
var operators:RegExp = /\+|\-|\*/g;
var numbers:RegExp = /\d+/g;


/**
 * Attempts to work with a mathematical formula provided as string.
 * @param str Subject string.
 */
function work(str:String):Number
{
    var ops:Array = str.match(operators);   // List of operators in order.
    var nums:Array = str.match(numbers);    // List of numbers in order.

    var command:Array = [];
    var cmbLen:int = Math.max(ops.length, nums.length);

    for(var i:int = 0; i < cmbLen; i++)
    {
        if(nums[i]) command.push(nums[i]);
        if(ops[i]) command.push(ops[i]);
    }


    // Begin performing the command.
    var val:Number = 0;
    var queuedOperator:String = "";

    for(i = 0; i < command.length; i++)
    {
        // Apply initial value;
        if(i == 0)
            val = Number(command[i]);

        // Work.
        if(i % 2 == 0)
        {
            var num:Number = Number(command[i]);

            // Operate if required.
            if(queuedOperator.length > 0)
            {
                switch(queuedOperator)
                {
                    case "+": val += num; break;
                    case "-": val -= num; break;
                    case "*": val *= num; break;
                }
            }

            queuedOperator = command[i + 1] as String || "";
        }
    }

    return val;
}

和一些测试:

trace(work("7 + 10")); // 17
trace(work("5 * 5")); // 25
trace(work("12 - 4")); // 8

trace(work("10 + 5 + 1")); // 16

随意在此基础上添加更多运算符(只需将它们添加到中operators)并按command优先级排序。添加()括号将开始变得有趣,但随着时间的推移,我确信可以正常工作。

于 2012-04-04T00:43:34.000 回答
0

这是使用RegExp的另一个解决方案。这可以使用以下符号计算整数和小数:^, %, /, *, +, -。您也可以使用括号,例如2^(10/(2+3-2)).

测试电影模式下,您需要从控制菜单中选择禁用键盘快捷键选项以查看结果。

import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.text.TextFieldAutoSize;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;


var tf:TextField = new TextField();
tf.addEventListener(KeyboardEvent.KEY_DOWN,tfKeyDown);
tf.defaultTextFormat = new TextFormat('_sans',24);
tf.autoSize = TextFieldAutoSize.LEFT;
tf.wordWrap = true;
tf.type = TextFieldType.INPUT;
tf.border = true;
tf.x = (stage.stageWidth - 300) * .5;
tf.y = 100;
tf.width = 200;
addChild(tf);
stage.focus = tf;


function tfKeyDown(e:KeyboardEvent):void {
    if (e.keyCode == Keyboard.ENTER) {
        e.preventDefault();
        trace('Input:',tf.text);
        trace('Result:',calculate(tf.text,7));
        trace('-----------------------');
    }
}

function calculate(str:String,maxDecimalCount:int=int.MAX_VALUE):Number {

    var num:String = '-?[0-9]*\\.?[0-9]+';
    var numRX:RegExp = new RegExp(num,'g');
    var rx:RegExp, i:int;

    // normalize minuses and eliminate spaces
    str = str.replace(/--/g,'+').replace(/\s/g,'');

    // calculate parenthesized equations
    while (/\(([^\(\)]+)\)/.test(str)) {
        str = str.replace(/\(([^\(\)]+)\)/g,function() {
            return calculate(String(arguments[1]),int.MAX_VALUE).toString();
        });
    }

    // exponential --> x^y
    rx = new RegExp(num+'(\\^'+num+')+','g');
    str = str.replace(rx,function() {
        var nums = String(arguments[0]).match(numRX);
        var res:Number = Math.pow(Number(nums[0]),Number(nums[1]));
        for (i = 2; i < nums.length; i++) res = Math.pow(res,Number(nums[i]));
        //trace('^ ['+nums+'] =',res);
        return res;
    });
    // modulus --> x%y
    rx = new RegExp(num+'(%'+num+')+','g');
    str = str.replace(rx,function() {
        var nums = String(arguments[0]).match(numRX);
        var res:Number = Number(nums[0]);
        for (i = 1; i < nums.length; i++) res %= Number(nums[i]);
        //trace('% ['+nums+'] =',res);
        return res;
    });
    // divide --> x/y
    rx = new RegExp(num+'(/'+num+')+','g');
    str = str.replace(rx,function() {
        var nums = String(arguments[0]).match(numRX);
        var res:Number = Number(nums[0]);
        for (i = 1; i < nums.length; i++) res /= Number(nums[i]);
        //trace('/ ['+nums+'] =',res);
        return res;
    });
    // multiply --> x*y
    rx = new RegExp(num+'(\\*'+num+')+','g');
    str = str.replace(rx,function() {
        var nums = String(arguments[0]).match(numRX);
        var res:Number = Number(nums[0]);
        for (i = 1; i < nums.length; i++) res *= Number(nums[i]);
        //trace('* ['+nums+'] =',res);
        return res;
    });
    // add or subtract --> x+y or x-y
    rx = new RegExp(num+'([\\+\\-]'+num+')+','g');
    str = str.replace(rx,function() {
        var nums = String(arguments[0]).match(numRX);
        var res:Number = Number(nums[0]);
        for (i = 1; i < nums.length; i++) res += Number(nums[i]);
        //trace('+- ['+nums+'] =',res);
        return res;
    });

    var res:Number = Number(str);
    // if the result is not a number...
    if (isNaN(res)) {
        throw new Error('Please input a valid equation using numbers and the following signs: ()^%/*+-');
    }
    // if the remainder needs to be shortened...
    if (maxDecimalCount < int.MAX_VALUE &&
        int(res) != res && String(res).split('.')[1].length > maxDecimalCount) {
        res = Math.round(res * Math.pow(10,maxDecimalCount)) / Math.pow(10,maxDecimalCount);
    }
    return res; 

}
于 2012-04-04T03:10:50.150 回答