I need to implement the following:
Input (a string):
5+45+100-125+5-10
Departure:
= 20
Here the code implemented only for positive numbers:
String operacion="10+200+3000";
int tam = operacion.length();
String A[] = new String[100];
int pos = 0;
int sum = 0;
String aux = "";
for(int i = 0; i<tam ; i++)
{
if(operacion.charAt(i) == '+')
{
A[pos] = aux;
pos++;
aux = "";
}
else
{
aux = aux + operacion.charAt(i);
}
}
A[pos] = aux;
pos++;
for(int i = 0; i<pos ; i++)
{
sum=sum+Integer.parseInt(A[i]);
}
System.out.println("= "+sum);
Departure
= 3210
The problem is that I can't do it for the negatives to do the operation.
One option would be to store the operators, and in the last loop, perform the respective operation:
This way you would get a correct calculation:
Bearing in mind that integers have a sign and that a subtraction is nothing more than the addition of a negative, I propose this more compact solution, also using regular expressions. Also check if there were spaces between signs and numbers as you can see in the input:
The output we get will be:
I would create another array to also store negative numbers. Let's call it B. And I would also create another integer to control the position.
And then in the condition we can use the structure
if-else if-else
as follows:The structure
if-else if-else
works in the same way as anif-else
although in this case it would be something like: "if it meets this condition do this, if it doesn't meet it check if it meets this other condition and if it meets it, do this other. If neither of the two checks are met, do this other".You'll actually be able to use the value of
aux
for both options since it re-initializes itself to empty each time a+
or a is found-
.Finally you can make a loop to subtract the negative numbers:
You can keep another vector with the signs, store them as you go through the chain and finally perform the operation, for example:
I have edited the code here, it probably contains some error, but I think that only by reading it you will understand the idea.
Add and subtract the numbers that are in a string. In the example that I put "5+45+100-125+5-10" the result is 20.
The fastest and easiest way is using regular expressions that match every number, both positive and negative. I leave you my code.
Greetings.