java - StringTokenizer.countTokens() returning erroneous value in for loop condition -
we have calculate numbers of "this" in given string having multiple "this" substrings. eg. "hello recruit , veteran , this" return 4.
so using:
stringtokenizer stringtokenizer1 = new stringtokenizer(input2); arraylist<string> arraylist1 = new arraylist<string>(); int count=0; int arrindex = stringtokenizer1.counttokens(); (int = 0; < stringtokenizer1.counttokens(); i++) { arraylist1.add(stringtokenizer1.nexttoken()); } (string string2 : arraylist1) { if (string2.equals(string)) { count++; } } output1 = count; system.out.println(output1);
return 2.
however, if int arrindex
assigned value of stringtokenizer1.counttokens() , used in looping condition, it's giving correct result of 4. why??
note:using javase-1.6
the condition stringtokenizer1.counttokens()
evaluated everytime reenter loop.
calculates number of times tokenizer's nexttoken method can called before generates exception. current position not advanced.
that means counttokens()
change everytime call nexttoken()
with example :
- for i=0, counttokens=4 -> enter loop -> call nexttoken() -> counttokens=3
- for i=1, counttokens=3 -> enter loop -> call nexttoken() -> counttokens=2
- for i=2, counttokens=2 -> exit loop
Comments
Post a Comment