Java Scanner useLocale() 方法



描述

Java Scanner useLocale(Locale locale) 方法將此掃描器的區域設定設定為指定的區域設定。

宣告

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

public Scanner useLocale(Locale locale)

引數

locale − 指定要使用的區域設定的字串

返回值

此方法返回此掃描器

異常

在字串上設定掃描器區域設定的示例

以下示例演示瞭如何使用 Java Scanner useLocale(Locale locale) 方法為掃描器使用區域設定。我們使用給定的字串建立了一個掃描器物件。我們使用 nextLine() 方法列印了一行,然後設定了一個區域設定來列印它。然後使用 close() 方法關閉掃描器。

package com.tutorialspoint;

import java.util.Scanner;
import java.util.Locale;
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);

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

      // change the locale of this scanner
      scanner.useLocale(Locale.ENGLISH);

      // display the new locale
      System.out.println(scanner.locale());

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

輸出

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

Hello World! 3 + 3.0 = 6.0 true 
en

在使用者輸入上設定掃描器區域設定的示例

以下示例演示瞭如何使用 Java Scanner useLocale(Locale locale) 方法來使用掃描器的區域設定。我們使用 System.in 類建立了一個掃描器物件。我們使用 nextLine() 方法列印了一行,然後設定了一個區域設定來列印它。然後使用 close() 方法關閉掃描器。

package com.tutorialspoint;

import java.util.Locale;
import java.util.Scanner;

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

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

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

      // change the locale of this scanner
      scanner.useLocale(Locale.ENGLISH);

      // display the new locale
      System.out.println(scanner.locale());

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

輸出

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

Hello World
Hello World
en

在屬性檔案上設定掃描器區域設定的示例

以下示例演示瞭如何使用 Java Scanner useLocale(Locale locale) 方法為掃描器設定區域設定。我們使用 properties.txt 檔案建立了一個掃描器物件。我們使用 nextLine() 方法列印了一行,然後設定了一個區域設定來列印它。然後使用 close() 方法關閉掃描器。

package com.tutorialspoint;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Locale;
import java.util.Scanner;

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

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

      // change the locale of this scanner
      scanner.useLocale(Locale.ENGLISH);

      // display the new locale
      System.out.println(scanner.locale());

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

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

Hello World! 3 + 3.0 = 6

輸出

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

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