| 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: 24054
|
|
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]
|
 |
 |
|
|
subject: Mathematically Adding String Tokens to equal a sum
|
|
|