Java Scanner skip() 方法



描述

Java Scanner skip(Pattern pattern) 方法跳過與指定模式匹配的輸入,忽略分隔符。如果指定模式的錨定匹配成功,則此方法將跳過輸入。如果在當前位置找不到與指定模式的匹配,則不跳過任何輸入,並丟擲 NoSuchElementException。

宣告

以下是 java.util.Scanner.skip() 方法的宣告

public Scanner skip(Pattern pattern)

引數

pattern - 指定要跳過的模式的字串

返回值

此方法返回此掃描器

異常

  • NoSuchElementException - 如果未找到指定的模式

  • IllegalStateException - 如果此掃描器已關閉

Java Scanner skip(String pattern) 方法

描述

Java Scanner skip(String pattern) 方法跳過與從指定字串構造的模式匹配的輸入。形式為 skip(pattern) 的此方法的呼叫與呼叫 skip(Pattern.compile(pattern)) 的方式完全相同。

宣告

以下是 java.util.Scanner.skip(String pattern) 方法的宣告

public Scanner skip(String pattern)

引數

pattern - 指定要跳過的模式的字串

返回值

此方法返回此掃描器

異常

IllegalStateException - 如果此掃描器已關閉

基於字串掃描器模式跳過令牌示例

以下示例演示瞭如何使用 Java Scanner skip(Pattern pattern) 方法跳過給定字串中的模式。我們使用給定字串建立了一個掃描器物件。我們使用 findAll(Pattern) 方法檢索了一個流。然後迭代流以列印結果。然後我們使用 scanner.nextLine() 方法列印了字串。

package com.tutorialspoint;

import java.util.Scanner;
import java.util.regex.Pattern;

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

      String s = "Hello World! 3 + 3.0 = 6.0 true ";

      // create a new scanner with the specified String Object
      Scanner scanner = new Scanner(s);

      // skip the word that matches the pattern ..llo
      scanner.skip(Pattern.compile("..llo"));

      // print a line of the scanner
      System.out.println(scanner.nextLine());

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

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

 World! 3 + 3.0 = 6.0 true 

基於字串掃描器字串跳過令牌示例

以下示例演示瞭如何使用 Java Scanner skip(String pattern) 方法跳過給定字串中的模式。我們使用給定字串建立了一個掃描器物件。我們使用 findAll(String) 方法檢索了一個流。然後迭代流以列印結果。然後我們使用 scanner.nextLine() 方法列印了字串。

package com.tutorialspoint;

import java.util.Scanner;

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

      String s = "Hello World! 3 + 3.0 = 6.0 true ";

      // create a new scanner with the specified String Object
      Scanner scanner = new Scanner(s);

      // skip the word that matches the pattern ..llo
      scanner.skip("..llo");

      // print a line of the scanner
      System.out.println(scanner.nextLine());

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

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

 World! 3 + 3.0 = 6.0 true 

基於使用者輸入掃描器模式跳過令牌示例

以下示例演示瞭如何使用 Java Scanner skip(String pattern) 方法跳過給定字串中的模式。我們使用 System.in 類建立了一個掃描器物件。我們使用 findAll(String) 方法檢索了一個流。然後迭代流以列印結果。然後我們使用 scanner.nextLine() 方法列印了字串。

package com.tutorialspoint;

import java.util.Scanner;

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

      // create a new scanner with the System input
      Scanner scanner = new Scanner(System.in);

      // skip the word that matches the pattern ..llo
      scanner.skip("..llo");

      // print a line of the scanner
      System.out.println(scanner.nextLine());

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

輸出

讓我們編譯並執行上述程式,這將產生以下結果:(我們輸入了 Hello World。)

Hello World
 World
java_util_scanner.htm
廣告