1. Overview
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. 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.
2.1. Syntax
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
2.2. Returns
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]*β).
3. Examples
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.
4. Conclusion
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.
