如何添加双字符,所以它像甲基化java一样工作

时间:2014-11-09 13:23:19

标签: java double character-arrays

我有两个arraylists,一个是double name =存储用户输入的数字(double),第二个是character name =运算符,用于存储用户输入的输入(+, - ,*,/)。 代码如下。 我希望当用户输入值时,代码应获取数字值并在操作符中输入操作。 请检查下面的代码并告诉我如何操作。

List<Double> numbers = new ArrayList<>();
List<Character> operators = new ArrayList<>();
........................

/* after getting input from user the code is now working as below.*/

void result() {
    et1.setText("");
    for (int i = 0; i < handler; i++) {
        double total2 = operators.get(i) + numbers.get(i);
        total3 += total2;
        et1.setText(Double.toString(total3));
    }

}
/*all values are just being add with eachother which are entered by the user.
help me how to solve this issue. */

2 个答案:

答案 0 :(得分:0)

基本上它不可能像你一样:

double total2= operators.get(i)+numbers.get(i);

您需要一个带有以下运算符的开关:

switch (operators.get(i)) {
    case '+':
         //do add
         break;
    case '-':
         //subtract
         break
    blah blah...
}

答案 1 :(得分:0)

试试这个:

void result() {

    et1.setText("");
    for (int i=0; i<handler;i++) {
        switch(operators.get(i)) {
            case '+':
                total3 += numbers.get(i);
                break;
            case '-':
                total3 -= numbers.get(i);
                break;
            case '*':
                total3 *= numbers.get(i);
                break;
            case '/':
                total3 /= numbers.get(i);
                break;
    et1.setText(Double.toString(total3));
    }           
}

这不是解决问题的最佳方法。阅读更多关于java 8中支持的地图和lambda的信息。你的地图应该如下所示(我知道c#中的lambdas,java必须有类似的东西。抱歉我的java)。这种方式使您的代码干净且可扩展:您不应为添加运算符(如^或%)添加更多开关 - 只需将键/值对添加到地图中。 Java与c#代码混合:/:

Map operations = HashMap<char, object>() { //in c# I use delegates instead object and i don't know type of lambda in java
{'+', (x, y) -> x + y},
{'-', (x, y) -> x - y},
{'*', (x, y) -> x * y},
{'/', (x, y) -> x / y},

}
total3 = operations.get(operators[i])(total3, total2);