I have a scanner that has been working smoothly up until I try the hasNext(Pattern) method to look for a leading ‘+’ character. Here’s what I have been trying to do:
File file = new File("Somefile.txt");
Scanner input = new Scanner(file);
while (!input.hasNext(Pattern.compile("^\\+"))) {
System.out.println("No leading +:" + input.next());
}
Which sure seems to make sense. However the program loops endlessly past plenty of lines with leading ‘+’. What am I doing wrong?
The problem is that you’re trying to match tokens against beginning-of-line with
^. The tokens will never contain new-lines to begin with (they will simply be the substrings that are separated by the delimiter), so^doesn’t make sense. If you want to read lines with the scanner, I suggest you doThen simply drop the
^and it will work: