sum和substract仅使用char和string

时间:2015-10-05 02:45:12

标签: string for-loop while-loop char

我必须使用+-字符制作一个能够对两个或更多数字进行求和和减去的代码

我设法得到了总和,但我不知道如何减去它。

以下是代码(我只允许使用forwhile循环):

int CM = 0, CR = 0, A = 0, PS = 0, PR = 0, LC = 0, D;
char Q, Q1;
String f, S1;
f = caja1.getText();

LC = f.length();
for (int i = 0; i < LC; i++) {
    Q = f.charAt(i);
    if (Q == '+') {
        CM = CM + 1;
    } else if (Q == '-') {
        CR = CR + 1;
    }
}
while (CM > 0 || CM > 0) {
    LC = f.length();
    for (int i = 0; i < LC; i++) {
        Q = f.charAt(i);
        if (Q == '+') {
            PS = i;
            break;
        } else {
            if (Q == '-') {
                PR = i;
                break;
            }
        }
    }
    S1 = f.substring(0, PS);

    D = Integer.parseInt(S1);

    A = A + D;

    f = f.substring(PS + 1);

    CM = CM - 1;

}
D = Integer.parseInt(f);
A = A + D;
salida.setText("resultado" + " " + A + " " + CR + " " + PR + " " + PS);

1 个答案:

答案 0 :(得分:0)

以下程序将解决在String

中给定方程式中执行加法和减法的问题

此示例程序在java中提供

public class StringAddSub {

public static void main(String[] args) {
    //String equation = "100+500-20-80+600+100-50+50";

    //String equation = "100";

    //String equation = "500-900";

    String equation = "800+400";

    /** The number fetched from equation on iteration*/
    String b = "";
    /** The result */
    String result = "";
    /** Arithmetic operation to be performed */
    String previousOperation = "+";
    for (int i = 0; i < equation.length(); i++) {

        if (equation.charAt(i) == '+') {
            result = performOperation(result, b, previousOperation);
            previousOperation = "+";

            b = "";
        } else if (equation.charAt(i) == '-') {
            result = performOperation(result, b, previousOperation);
            previousOperation = "-";
            b = "";
        } else {
            b = b + equation.charAt(i);
        }
    }

    result = performOperation(result, b, previousOperation);
    System.out.println("Print Result : " + result);

}

public static String performOperation(String a, String b, String operation) {
    int a1 = 0, b1 = 0, res = 0;
    if (a != null && !a.equals("")) {
        a1 = Integer.parseInt(a);
    }
    if (b != null && !b.equals("")) {
        b1 = Integer.parseInt(b);
    }

    if (operation.equals("+")) {
        res = a1 + b1;
    }

    if (operation.equals("-")) {
        res = a1 - b1;
    }
    return String.valueOf(res);
}

}