java.util.Scanner has many methods that we can use to validate inputs. One of these is the skip() method.
In this tutorial, we'll learn what the skip() method is for and how to use it.
2. java.util.Scanner.skip() Method
The skip() method belongs to the Java Scanner class. It is used to skip inputs that match a specified pattern passed in the method parameter, ignoring delimiters.
The skip() method has two overloaded method signatures:
- skip(Pattern pattern) – takes as a parameter the pattern that the Scanner should skip
- skip(String pattern) – takes as a parameter a String specifying the pattern to skip
skip() returns a Scanner object that satisfies the pattern specified in the method argument. It can also throw two types of exceptions: IllegalStateException if the scanner is closed, and NoSuchElementException if no match is found for the specified pattern.
Note that it's possible to skip something without risking a NoSuchElementException by using a pattern that cannot match anything – for example, skip(“[ \t]*”).
As we mentioned earlier, the skip method has two overloaded forms. First, let's see how to use the skip method with a Pattern:
String str = "Java scanner skip tutorial"; Scanner sc = new Scanner(str); sc.skip(Pattern.compile(".ava"));
Here, we've used the skip(Pattern) method to skip text that meets the “.ava” pattern
Likewise, the skip(String) method will skip text that meets the given pattern constructed from the given String. In our example, we skip the string “Java”:
String str = "Java scanner skip tutorial"; Scanner sc = new Scanner(str); sc.skip("Java");
In short, the result of both methods is the same using either the pattern or the string.
In this short article, we've checked how to work with the skip() method of the java.util.Scanner class using either a String or Pattern parameter.
As always, the code used during the discussion is available over on GitHub.