Scanner throws NoSuchElementException when used with a spatial template

I am trying to read the specified file format with Scanner and Pattern input, for example:

 Pattern p = Pattern.compile("\\d+\\sx\\s\\d+"); Scanner sc = new Scanner(System.in); String input = ""; try { input = sc.next(p); } catch(NoSuchElementException ne) { System.out.println("No such token"); } sc.close(); System.out.println(input); 

But when I use 1 x 1 for input, it throws NoSuchElementException
When using the \\d+x\\d+ template and 1x1 input, it works, but not with spaces in the template, am I doing something wrong?

+4
source share
1 answer

The documentation says:

The scanner splits its input into tokens using the delimiter pattern, which by default matches a space. The resulting markers can then be converted to different types using the following various methods.

And he also says:

public String next (template template)

Returns the next token if it matches the specified template.

So, your code reads the characters to the next space and returns them if they match your pattern. This is not the case, since your template matches strings containing a space, and the token cannot contain one.

+6
source

All Articles