Method to take in a string sentence and reverse the tokens
Code :
import java.util.StringTokenizer;
public class StringTokens{
public String reverseWords(String sentence){
StringTokenizer tokens = new StringTokenizer(sentence);
String result = "";
while(tokens.hasMoreTokens()){
String[] t = new String[10];
for(int j = 0; j < sentence.length(); j++){
t[j] = tokens.nextToken();
}
for(int k = sentence.length()-1; k >= 0; k--){
result = result + t[k];
}
}
return result;
}
}
The code above compiles but then gives me an error saying "java.util.NoSuchElementException" I believe referring to line 12
Code :
t[j] = tokens.nextToken();
Re: Method to take in a string sentence and reverse the tokens
This error comes from how you have the for loop set up. Lets say that sentence = "hello how are you doing today". The length of sentence would be 29 and your loop would therefore use the numbers 0 thru 28. In this case, this would be a problem on 2 fronts:
1) There are only 6 tokens in "hello how are you doing today"
2) The size of t is only 10
So, once the loop gets to j = 6, the tokens in the sentence have already been added and there are no more left hence the error.