VOOZH about

URL: https://www.geeksforgeeks.org/java/scanner-skip-method-in-java-with-examples/

⇱ Scanner skip() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Scanner skip() method in Java with Examples

Last Updated : 11 Jul, 2025

skip(Pattern pattern)

The skip(Pattern pattern) method of java.util.Scanner class skips input that matches the specified pattern, ignoring the delimiters. The function skips the input if an anchored match of the specified pattern succeeds it. Syntax:
public Scanner skip(Pattern pattern)
Parameters: The function accepts a mandatory parameter pattern which specifies a string as pattern to be skipped. Return Value: The function returns this scanner Exceptions: This method throws following exceptions:
  • NoSuchElementException: when the specified pattern is not found
  • IllegalStateException: when this scanner is closed
Below programs illustrate the above function: Program 1:
Output:
String trying to get input:
GeeksForGeeks - A Computer Science Portal for Geeks
Skipping 5 letter words that ends with 'eks'

Input Scanner String: 
ForGeeks - A Computer Science Portal for Geeks
Program 2: To demonstrate NoSuchElementException
Output:
String trying to get input:
GeeksForGeeks - A Computer Science Portal for Geeks
Skipping 3 letter words and

Exception thrown: java.util.NoSuchElementException
Program 3: To demonstrate IllegalStateException
Output:
String trying to get input:
GeeksForGeeks - A Computer Science Portal for Geeks
Scanner Closed
Trying to Skip 3 letter words and

Exception thrown: java.lang.IllegalStateException: Scanner closed

skip(String pattern)

The skip(String pattern) method of java.util.Scanner class skips the input that matches with the pattern constructed from the specified string. The skip(pattern) and skip(Pattern.compile(pattern)) behaves exactly the same way on being called. Syntax:
public Scanner skip(String pattern)
Parameters: The function accepts a mandatory parameter string pattern which specifies a string denoting the pattern to skip over Return Value: The function returns this scanner Exceptions: This method throws IllegalStateException when this scanner is closed Below programs illustrate the above function: Program 1:
Output:
String trying to get input:
GeeksForGeeks - A Computer Science Portal for Geeks
Skipping 5 letter words that ends with 'eks'

Input Scanner String: 
ForGeeks - A Computer Science Portal for Geeks
Program 2: To demonstrate IllegalStateException
Output:
String trying to get input:
GeeksForGeeks - A Computer Science Portal for Geeks
Scanner Closed
Trying to Skip 3 letter words and

Exception thrown: java.lang.IllegalStateException: Scanner closed
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#skip(java.util.regex.Pattern)
Comment