📌  相关文章
📜  Java中的 Locale.Builder setLanguage() 方法及示例

📅  最后修改于: 2022-05-13 01:54:23.500000             🧑  作者: Mango

Java中的 Locale.Builder setLanguage() 方法及示例

Java中Java .util.Locale.Builder类setLanguage(String)方法用来设置这个Locale.Builder为指定的语言。这意味着此方法将设置 Locale.Builder 实例的当前语言以匹配提供的语言并返回它。如果指定的语言为 null 或为空,则移除此 LocaleBuilder 的语言。

句法:

public Locale.Builder
  setLanguage(String language)

参数:此方法接受语言作为参数,该参数是要设置为此 Locale.Builder 实例的字符串。

返回值:此方法返回一个Locale.Builder 实例,此 Locale.Builder 的语言设置为指定的语言。

异常:此方法抛出以下异常:

  • IllformedLocaleException : 如果指定的语言有任何格式错误的字段

方案一:

// Java program to demonstrate
// the above method
  
import java.util.*;
import java.util.Locale.*;
  
public class LocaleBuilderDemo {
    public static void main(String[] args)
    {
  
        // Creating a new Locale.Builder
        Locale.Builder localeBuilder
            = new Builder();
  
        // Displaying Locale.Builder
        System.out.println("LocaleBuilder: "
                           + localeBuilder);
  
        // setting the language of Locale.Builder
        String language = "FRENCH";
        System.out.println("Setting the language: "
                           + language);
  
        localeBuilder
            = localeBuilder.setLanguage(language);
  
        // Displaying Locale.Builder
        System.out.println("Updated LocaleBuilder: "
                           + localeBuilder);
    }
}
输出:
LocaleBuilder: java.util.Locale$Builder@232204a1
Setting the language: FRENCH
Updated LocaleBuilder: java.util.Locale$Builder@232204a1

方案二:

// Java program to demonstrate
// the above method
  
import java.util.*;
import java.util.Locale.*;
  
public class LocaleBuilderDemo {
    public static void main(String[] args)
    {
  
        // Creating a new Locale.Builder
        Locale.Builder localeBuilder
            = new Builder();
  
        // Displaying Locale.Builder
        System.out.println("LocaleBuilder: "
                           + localeBuilder);
  
        // setting the language of Locale.Builder
        String language = "asdasf@!vsd#";
        System.out.println("Setting the language: "
                           + language);
          
        try{
        localeBuilder
            = localeBuilder.setLanguage(language);
  
        // Displaying Locale.Builder
        System.out.println("Updated LocaleBuilder: "
                           + localeBuilder);
                           }
        catch(Exception e)
        {
            System.out.println(e);
            }
    }
}
输出:
LocaleBuilder: java.util.Locale$Builder@232204a1
Setting the language: asdasf@!vsd#
java.util.IllformedLocaleException: Ill-formed language: asdasf@!vsd# [at index 0]

参考: https://docs.oracle.com/javase/9/docs/api/ Java/util/Locale.Builder.html#setLanguage-java.lang.String-