2015-10-05 66 views
0

我不得不做出這樣的總和減去使用+-字符總和。減去使用字符和字符串只

我設法使之和兩個或兩個以上數字的代碼,但我對如何不知道使其減去。

下面是代碼(我只允許使用的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); 
+0

您需要標記您的編程語言。 – DarkKnight

回答

0

下面的程序將解決您的字符串

在給定的公式進行加法和減法的問題

此範例程序是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); 
} 

}

給出