1. Overview
1.概述
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
2.Scanner.skip()方法
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()方法有两个重载方法签名。
- 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
2.2.回报
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]*”).
请注意,通过使用一个不能匹配任何东西的模式,可以跳过一些东西而不会有NoSuchElementException的风险,例如,skip(“[\t]*”)。
3. Examples
3.例子
As we mentioned earlier, the skip method has two overloaded forms. First, let’s see how to use the skip method with a Pattern:
正如我们前面提到的,skip方法有两种重载形式。首先,让我们看看如何使用skip方法与Pattern。
String str = "Java scanner skip tutorial";
Scanner sc = new Scanner(str);
sc.skip(Pattern.compile(".ava"));
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);
sc.skip("Java");
In short, the result of both methods is the same using either the pattern or the string.
简而言之,使用模式或字符串,两种方法的结果是一样的。
4. Conclusion
4.结论
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.
在这篇短文中,我们检查了如何使用java.util.Scanner类的skip()方法,使用String或Pattern参数。
As always, the code used during the discussion is available over on GitHub.
一如既往,讨论中使用的代码可在GitHub上找到。