Java Scanner tokens() 方法



描述

java Scanner tokens() 方法返回從此掃描器獲取的分隔符分隔的標記流。該流包含從掃描器的當前狀態開始,透過重複呼叫 next() 方法直到 hasNext() 方法返回 false 所返回的相同標記。生成的流是順序的且有序的。所有流元素均非空。

宣告

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

public Stream<String> tokens()

引數

返回值

此方法返回從輸入掃描的 BigDecimal

異常

  • InputMismatchException − 如果下一個標記與十進位制正則表示式不匹配,或超出範圍

  • NoSuchElementException − 如果輸入已耗盡

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

在字串示例上獲取掃描器的標記流

以下示例演示了 Java Scanner tokens() 方法的使用,以獲取掃描的標記流。我們使用給定的字串建立了一個掃描器物件。然後,我們使用 tokens() 方法獲取標記流並迭代它們以進行列印。最後,使用 close() 方法關閉掃描器。

package com.tutorialspoint;

import java.util.Scanner;
import java.util.stream.Stream;

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

      String s = "Hello World! 3 + 3.0 = 6";

      // create a new scanner with the specified String Object
      Scanner scanner = new Scanner(s);
      
      Stream<String&t; tokens = scanner.tokens();
      
      tokens.forEach(t -> System.out.println(t));

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

輸出

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

Hello
World!
3
+
3.0
=
6

在使用者輸入示例上獲取掃描器的標記流

以下示例演示了 Java Scanner tokens() 方法的使用,以獲取掃描的標記流。我們使用 System.in 類建立了一個掃描器物件。然後,我們使用 tokens() 方法獲取標記流並迭代它們以進行列印。最後,使用 close() 方法關閉掃描器。

package com.tutorialspoint;

import java.util.Scanner;
import java.util.stream.Stream;

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

      // create a new scanner with the System input
      Scanner scanner = new Scanner(System.in);
      
      Stream<String&t; tokens = scanner.tokens();
      
      tokens.forEach(t -> System.out.println(t));

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

輸出

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

Hello World
Hello
World

在屬性檔案示例上獲取掃描器的標記流

以下示例演示了 Java Scanner tokens() 方法的使用,以獲取掃描的標記流。我們使用檔案 properties.txt 建立了一個掃描器物件。然後,我們使用 tokens() 方法獲取標記流並迭代它們以進行列印。最後,使用 close() 方法關閉掃描器。

package com.tutorialspoint;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.stream.Stream;

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

      // create a new scanner with a file as input
      Scanner scanner = new Scanner(new File("properties.txt"));
         
      Stream<String&t; tokens = scanner.tokens();
      
      tokens.forEach(t -> System.out.println(t));

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

假設我們在你的 CLASSPATH 中有一個名為 properties.txt 的檔案,其內容如下。此檔案將用作我們示例程式的輸入:

Hello World! 3 + 3.0 = 6

輸出

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

Hello
World!
3
+
3.0
=
6
java_util_scanner.htm
廣告