Java Scanner.skip method with examples – Java Scanner.skip方法与实例

最后修改: 2022年 4月 30日

1. Overview


java.util.Scanner has many methods that we can use to validate inputs. One of these is the skip() method.

java.util.Scanner有许多方法,我们可以用它们来验证输入。其中一个是skip()/em> 方法。

In this tutorial, we’ll learn what the skip() method is for and how to use it.

在本教程中,我们将学习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.

skip()方法属于Java Scanner类。它被用来跳过与方法参数中传递的指定模式相匹配的输入,忽略了分隔符。

2.1. Syntax

2.1 语法

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.

skip() 返回一个满足方法参数中指定模式的Scanner对象。它还可以抛出两种类型的异常IllegalStateException如果扫描器被关闭,以及NoSuchElementException如果没有找到与指定模式匹配的对象。

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); 

Here, we’ve used the skip(Pattern) method to skip text that meets the “.ava” pattern

在这里,我们使用skip(Pattern)方法来跳过符合”.ava “模式的文本。

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”:

同样,skip(String) 方法将跳过符合由给定String构建的给定模式的文本。在我们的例子中,我们跳过 “Java “这个字符串。

String str = "Java scanner skip tutorial";
Scanner sc = new Scanner(str); 

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.


As always, the code used during the discussion is available over on GitHub.