Home »
Java programming language
Java Scanner skip() Method with Example
Scanner Class skip() method: Here, we are going to learn about the skip() method of Scanner Class with its syntax and example.
Submitted by Preeti Jain, on March 24, 2020
Scanner Class skip() method
Syntax:
public Scanner skip(Pattern patt);
public Scanner skip(String patt);
- skip() method is available in java.util package.
- skip(Pattern patt) method is used to skip input that meets the given pattern, avoiding delimiters.
- skip(String patt) method is used to skip input that meets the pattern formed from the given string (patt).
-
These methods may throw an exception at the time of skipping input that meets the given pattern.
- NoSuchElementException: This exception may throw when the given pattern does not exist.
- IllegalStateException: This exception may throw when this Scanner is not opened.
- These are non-static methods and it is accessible with the class object only and if we try to access these methods with the class name then we will get an error.
Parameter(s):
-
In the first case, skip(Pattern patt),
- Pattern patt – represents the pattern to skip.
-
In the second case, skip(String patt),
- String patt – represents a string denoting the pattern to skip.
Return value:
In both the cases, the return type of the method is Scanner, it retrieves this Scanner object.
Example 1:
// Java program to demonstrate the example
// of skip() method of Scanner
import java.util.*;
import java.util.regex.*;
public class Skip {
public static void main(String[] args) {
String str = "Java Programming! 3 * 8= 24";
// Instantiates Scanner
Scanner sc = new Scanner(str);
// By using skip(Pattern) method
// is to skip that meets the given
// pattern
sc.skip(Pattern.compile(".ava"));
System.out.println("sc.skip(): " + sc.nextLine());
// Scanner closed
sc.close();
}
}
Output
sc.skip(): Programming! 3 * 8= 24
Example 2:
import java.util.*;
import java.util.regex.*;
public class Skip {
public static void main(String[] args) {
String str = "Java Programming! 3 * 8= 24";
// Instantiates Scanner
Scanner sc = new Scanner(str);
// By using skip(String) method
// is to skip that meets the given
// pattern constructed from the given
// String
sc.skip("Java");
System.out.println("sc.skip(Java): " + sc.nextLine());
// Scanner closed
sc.close();
}
}
Output
sc.skip(Java): Programming! 3 * 8= 24