Java Utility Library

Java Scanner - skip() Method



The java.util.Scanner.skip() method is used to skip input that matches the specified pattern, ignoring delimiters. This method will skip input if an anchored match of the specified pattern succeeds.

If a match to the specified pattern is not found at the current position, then no input is skipped and a NoSuchElementException is thrown.

Syntax

public Scanner skip(Pattern pattern)

Parameters

pattern Specify the pattern to skip over.

Return Value

Returns the scanner.

Exception

  • Throws NoSuchElementException, if the specified pattern is not found.
  • Throws IllegalStateException, if this scanner is closed.

Example:

In the example below, the java.util.Scanner.skip() method is used to skip input that matches the specified pattern, ignoring delimiters.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {

    //String to scan
    String MyString = "Hello World 10 + 20 = 30.0";

    //creating a Scanner
    Scanner MyScan = new Scanner(MyString);

    //skip the first word if matches the pattern .ello
    MyScan.skip(".ello");
      
    //print the rest of the line
    System.out.println(MyScan.nextLine());

    //close the scanner
    MyScan.close();
  }
}

The output of the above code will be:

 World 10 + 20 = 30.0

Example:

In the example below, java.util.Scanner.skip() method is used to skip first occurrence of the specified pattern from the scanner.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {

    //String to scan
    String MyString = "Hello 10 20 30 40 50";

    //creating a Scanner
    Scanner MyScan = new Scanner(MyString);

    while(MyScan.hasNext()) {
      //skip the first occurrence of the pattern
      MyScan.skip("[a-zA-Z]*");
      
      //print the rest of the line
      System.out.println(MyScan.next());
    }

    //close the scanner
    MyScan.close();
  }
}

The output of the above code will be:

10
20
30
40
50

❮ Java.util - Scanner