• Post Reply Bookmark Topic Watch Topic
  • New Topic

String to math operation  RSS feed

 
Kirby Araullo
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!



 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.


 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is this an exercise that specifically disallows the use of the BigInteger class?
 
Kirby Araullo
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Ulf Dittmer not actually, as long as you follow what the instruction's said and produce the right output.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, using BIgInteger you could replace lines 7 through 15 with a single line of code.
 
Nivedita Gautam
Greenhorn
Posts: 3
C++ Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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++)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!