The Java Scanner Skip Method: Syntax, Examples, and Explanations
Java Scanner.skip Method With Examples
The java.util.Scanner.skip(Pattern pattern) method skips input that matches the specified pattern, ignoring the scanned input. In other words, it skips past the current line and discards any input data in the buffer.
Syntax
public Scanner skip(Pattern pattern)
Parameters
pattern
: The scanning will skip input that matches this pattern.
Returns
This scanner.
Example 1
In this example, we create a Scanner to read from a file, and use the skip() method to skip any lines that start with "//".
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class SkipExample { public static void main(String[] args) { try { File file = new File("input.txt"); Scanner sc = new Scanner(file); while (sc.hasNextLine()) { String line = sc.nextLine(); if (line.startsWith("//")) { sc.skip(line); } else { System.out.println(line); } } sc.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
Example 2
In this example, we create a Scanner to read from a String, and use the skip() method to skip any input that is a digit.
import java.util.Scanner; public class SkipExample { public static void main(String[] args) { String inputText = "Hello 1 World 2"; Scanner sc = new Scanner(inputText); while (sc.hasNext()) { String token = sc.next(); if (token.matches("\\d+")) { sc.skip(token); } else { System.out.println(token); } } sc.close(); } }
Example 3
In this example, we create a Scanner to read from a file, and use the skip() method to skip the first line of input that contains some specific text.
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class SkipExample { public static void main(String[] args) { try { File file = new File("input.txt"); Scanner sc = new Scanner(file); sc.skip("# START OF FILE"); while (sc.hasNextLine()) { System.out.println(sc.nextLine()); } sc.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }