Bill Mackie

Greenhorn

Posts: 9

posted 12 years ago

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.

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.

posted 12 years ago

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!

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!