I notice that my method doesn't work even though I tried to get it's while-loop set-up to do the following things:
- Have each token of a string get put into another one
- Replace each given-substring (string2) with it's assigned-replacement (string3) as the string's (string1) tokens pass by
- Have it's final answer returned as a variable to the main-method
Here is my code that has each of it's parts with a comment...
// For the replacement of a substring with another one. public static String replaceSubstring(String string1, String string2, String string3) { Scanner keys = new Scanner(System.in); // Use a StringTokenizer-object for breaking a string // down to the point of finding that matching-substring // in general. StringTokenizer numOne = new StringTokenizer(string1, " ", true); StringTokenizer num1 = new StringTokenizer(string1, " ", true); StringTokenizer numWon = new StringTokenizer(string1, " ", true); String attacher = new String(); // Find the substring with the while-loop. while (numOne.hasMoreTokens()) { if (num1.nextToken() == string2) { attacher += string3; } if (numWon.nextToken() != string2) { attacher += numWon.nextToken(); } } // Finally, return the String-object. return attacher; }
...and here is the output-part I want to avoid at runtime.
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenize r.java:349)
at MiscellaneousStr.replaceSubstring(MiscellaneousStr .java:93)
at MiscellaneousSDemo.main(MiscellaneousSDemo.java:84 )
So as you can see, I have to avoid getting a message that refers to having no more elements in an enumeration.
Any suggestions?