I want to create a method that iterates through any String (that is one word long) one character at a time and prints out every character on a new line using delimiters. To do this, I read all about regular expressions (this post helped me the most for learning them), and the Java documentation on how to compile a Pattern to use in a Scanner (here and here). After learning all of this, I created the following code:
public static void stringPrinter(String whole){
Pattern p = Pattern.compile(".{1}");
Scanner scan = new Scanner(whole);
scan.useDelimiter(p);
for (int i = 0; i < whole.length(); i++){
System.out.println(scan.next());
}
}
I then ran a test of it with this line:
stringPrinter("okay");
Now in my head, this should work as follows:
- It takes in a String and sets it to the variable name
whole
. - It compiles a Pattern saved to the variable
p
, that is comprised of any one character. - It creates a Scanner object that is set to scan the String
whole
. - It sets the delimiter of the scanner to that Pattern
p
that we defined (so it will stop after every one character it finds). - It will run a loop that will run exactly as many times as their are characters in the String
whole
. - The statement that it will run that many times finds one character, and then prints that out to the console.
So I would expect the output 'o', 'k', 'a', and 'y' each on their own lines.
But the actual output it gives is:
.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at WholeNumber.stringPrinter(WholeNumber.java:37)
at WholeNumber.main(WholeNumber.java:28)
.
(Except that there are not those periods. There are just three blank lines on top and a blank line beneath. I added those periods so the whitespace would show up here).
I assume that the stack trace has something to do with it iterating one extra time but there not being a new character. Yet even if I comment out the second to last line of my code (where the for loop is declared) I still get this output:
.
(just a blank line)
So could someone help me figure out what's going on? I'm really not sure what's wrong with this program. Any help is appreciated so thanks in advance!
P.S. And yes, I checked this post before posting this question. It confirmed my impression that .
should check for any character and {1}
after it should make sure it is looking for exactly one character.