user19951215
user19951215

Reputation: 111

countTokens() method misbehave when using directly in loop

countTokens() method returns 3 instead of 5 when i am using in for loop.

	public static void main(String[] args) {
		String s = "foo1,foo2,foo3,foo4,foo5";
		StringTokenizer tokenizer = new StringTokenizer(s, ",");
		System.out.println(tokenizer.countTokens()); // countTokens() return 5
		for (int i = 0; i < tokenizer.countTokens(); i++) // countTokens() return 3
		{
			System.out.println(tokenizer.nextElement());
		}

	}

OUTPUT

5
foo1
foo2
foo3

can anyone let me know the reason?

Upvotes: 2

Views: 47

Answers (1)

dbasurco
dbasurco

Reputation: 91

The reason is becaus when you use

tokenizer.nextElement()

There are one token less, in this case, each use ofi it, reduce the element counted by

tokenizer.countTokens()

try that:

    for (int i = 0; i < tokenizer.countTokens(); i++) 
    {
        System.out.println(tokenizer.countTokens());
        System.out.println(tokenizer.nextElement());
    }

for see it, and that:

    while (tokenizer.hasMoreTokens()) {
        System.out.println(tokenizer.nextElement());
    }

for look all the elements correctly.

Regards,

Upvotes: 2

Related Questions