File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Mathematically Adding String Tokens to equal a sum Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Mathematically Adding String Tokens to equal a sum" Watch "Mathematically Adding String Tokens to equal a sum" New topic
Author

Mathematically Adding String Tokens to equal a sum

Bill Mackie
Greenhorn

Joined: Nov 27, 2004
Posts: 9
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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!


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Mathematically Adding String Tokens to equal a sum