• Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubt  RSS feed

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI ,
can anyone help me regarding this java program For example, s="12 some text 3 7", result: 22 (12+3+7=22)

i want logic for this program please help me...
 
Ranch Hand
Posts: 445
1
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Split the entire String into a char array. Convert each character into its numeric equivalent and add up all the numbers.
 
Roopa Bhuvaneswari
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Convert each character into its numeric equivalent ..it is not clear can you please explain me clearly
 
Marshal
Posts: 56608
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roopa Bhuvaneswari wrote: . . . i want logic for this program please help me...
You will have to work out the logic for your programs yourself, I am afraid. Write it down on paper, then you can see what you are doing. And are yoiu sure that
"12 some text 3 7"
. . . actually gives 22 by any straightforward means?
 
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't (easily) do it character by character, because of multi-digit numbers (e.g. 12).

Once thing you could do is use String.split() to split on non-numeric characters. That will give you an array of strings that can easily be converted to a number. That would work as long as all the values you're looking for are non-negative integers with simple formatting. If you need to cope with decimals, or with negative numbers, then the problem gets quite a bit more complicated.
 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to convert the Strings "12", "3" and "7" into numbers (ints) 12, 3 and 7. java.lang.Integer has a nice static method for this; check out the class' Javadoc page. Be aware that you should catch the exception that will be thrown when you pass "some" or "text" to this method.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!