【问题标题】:sum and substract using char and string only仅使用 char 和 string 进行求和和减法
【发布时间】:2023-03-13 15:46:01
【问题描述】:

我必须编写一个代码,使用 +- 字符对两个或多个数字进行加减运算

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

这是代码(我只能使用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);

【问题讨论】:

  • 您需要标记您的编程语言。

标签: string for-loop while-loop char


【解决方案1】:

以下程序将解决您在字符串中的给定方程中执行加法和减法的问题

这个示例程序是用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);
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-06
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2012-05-29
    • 2011-12-30
    • 2011-04-21
    相关资源
    最近更新 更多