简体   繁体   中英

sum and substract using char and string only

I have to make a code that sums and subtracts two or more numbers using the + and - chars

I managed to make the sum, but I have no idea on how to make it subtract.

Here is the code (I'm allowed to use the for and while loops only):

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);

The following program will solve your problem of performing addition and subtraction in a given equation in String

This sample program is given in 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);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM