我有一个字符串,其中包含操作(+,-),其他包含(+,-,*,/)
链如下:
String myString = "-18+65-14+78"
=> 111
String myString3 = "-69*18+14-22*-75"
=> 422
我用此代码分割
public class Test2 {
public static void main(String[] args) {
String myString = "18+65-14+78";
String[] str = myString.split("[-\\+]");
int s = 0;
for (int i = 0; i < str.length; i++) {
s += Double.parseDouble(str[i]);
System.out.println(str[i]);
}
System.out.println("the sum is : " + s);
}
}
当我在链的开头使用-时,错误是空字符串
如何用(+和-)运算符以及另一个运算符(*)解决问题?
答案 0 :(得分:0)
如果您只想求解(+,-),这很容易。只需拆分数字并添加或替换它们即可。源代码如下:
import java.io.*;
import java.util.*;
public class Main {
public static void main (String[] args) {
String str = "-18+65-14+78";
String temp = "0";
double sum = 0.0;
char prev = '+';
for(char ch: str.toCharArray()) {
if(ch == '+' || ch == '-') {
if(prev == '+') sum = sum + Double.parseDouble(temp);
else sum = sum - Double.parseDouble(temp);
prev = ch;
temp = "0";
}
else temp = temp + ch;
}
if(prev == '+') sum = sum + Double.parseDouble(temp);
else sum = sum - Double.parseDouble(temp);
System.out.println(sum);
}
}
现在,如果必须对(+,-,*,/)执行此操作,则它有点复杂。好吧,让我们看看是否可以为您分解一下。希望您以前使用后缀符号进行介绍。如果没有,您可以在这里Reverse Polish notation or Postfix Notation看到。
In a simple description:
(1) Infix: A + B
Postfix: A B +
(2) Infix: A + B * C
Postfix: A B C * +
您知道(*,/)的优先级高于(+,-),因此我们无法像(+,-)那样计算它。
Let us take an equation A+B*C-D*Q
which is actually A+(B*C)-(D*Q)
因此,我们必须以一种没有括号的方式并有序地表示它,以便我们可以正确地计算出它。
Let's observe the part A+B*C i.e. A+(B*C)
If we represent it in Postfix, it would be like: A B C * +
Now, the algorithm to calculate it
(1) Take a stack
(2) When we see a number, we push it to stack
(3) When we see a operator, we pop two numbers out of stack and calculate them with help of operator and push the result into stack again
(4) We do it till the end
(5) At last, only a number would be left in stack, that is our answer.
Let's visualise it:
(1) [A]
(2) [A, B]
(3) [A, B, C]
(4) [A, R1] where R1 = B*C
(5) [R2] where R2 = A+R1
现在,主要问题是A +(BxC)-(DxQ),在Postfix A B C * + D Q *-
我希望您可以自己做,并创建一个算法来解决问题。您将获得大量用于将中缀转换为后缀表示法的源代码,或者您可以自己编写一个。