This week's book giveaway is in the OCP forum.We're giving away four copies of OCP Java SE 8 Programmer II Exam Study Guide and have Kathy Sierra, Bert Bates, & Elizabeth Robson on-line!See this thread for details.
Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# String to math operation

Greenhorn
Posts: 4
Good day!
Given a string of numbers and operator. Compute as follows:
Consider, "000293000002030403+0400293059694" is the input.
a. Separate the two operands and one operator:
"000293000002030403" "+" "0400293059694"
b. On each string operand, take each digit. ADD them all.
(2+9+3+2+3+4+3) + (4+2+9+3+5+9+6+9+4)
The two string operands should now become two integers.
c. Lastly, perform the operation using the string operator specified on the original string.
26 + 51 = 77
I don't know why I get the sum of 52 when I use a for loop.
Here are my codes: Thanks!

Bartender
Posts: 3648
16
Hello

First you are using a char array to represents the number. Adding char and int gives unexpected result. To just change the char value to int you can either make a int array or do the shortcut adding "- '0'" to the sum variable

Second your sum is not accumulating the previous result, you are just assigning the last result to the sum variable.

Third the for loop's end point is NOT firstOp.length-1 but firstOp.length. If -1 you will have ignored/missed the last number.

Bartender
Posts: 3307
86
Other things to consider are:
1. You are splitting the string on '+', but what if the operand is '-' or '*' etc. Maybe you should split the string on not-a-digit.
2. When you find yourself doing the same thing multiple times (ie summing firstOpera and secondOpera requires the same code, the only difference is the String you are summing) then it is generally time to use a method so you only have to write the code once.
3. You may also want to read MainIsAPain

Rancher
Posts: 42975
76
Is this an exercise that specifically disallows the use of the BigInteger class?

Kirby Araullo
Greenhorn
Posts: 4
@Ulf Dittmer not actually, as long as you follow what the instruction's said and produce the right output.

Ulf Dittmer
Rancher
Posts: 42975
76
Well, using BIgInteger you could replace lines 7 through 15 with a single line of code.

Greenhorn
Posts: 3
Why are you looping till <firstOp.length - 1 only ??

for(int i = 0 ; i < firstOp.length - 1; i++)

make it:

for(int i = 0 ; i < firstOp.length; i++)