This week's book giveaway is in the Beginning Java forum.
We're giving away four copies of Murach's Java Programming and have Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Mathematically Adding String Tokens to equal a sum  RSS feed

 
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
Sheriff
Posts: 24217
38
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!
 
when your children are suffering from your punishment, tell your them it will help them write good poetry when they are older. Like this tiny ad:
Thoughts on deprecation in Java
https://coderanch.com/t/683016/java/Deprecation-Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!