• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mathematically Adding String Tokens to equal a sum

 
Bill Mackie
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
TWIMC,

I am trying to mathematically add individual tokens of character data.

For instance:
StringTokenizer st = new StringTokenizer("5 10 15 20");
while (st.hasMoreTokens())
{
System.out.println("The sum of the integers equals: "
+ st.???());
}

output: The sum of the integers equals: 50

Is there a way I can write the code to only add 1st, 3rd, 5th or every other token?
output: The sum of the integers equals: 20

I have looked through the API Strings section.....can't find the answer. I will check under Math.....

Thanks for your help.....peanut was not built for JAVA.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The most important piece of the puzzle is the static method Integer.parseInt(), which takes a String as an argument and returns an int; you can then add these ints.

As far as doing something with every other one: sure, just call nextToken() twice per loop, and throw the result away one of the times. You have to be careful if there are an odd number of tokens, of course!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic