Java中的 Locale.Builder setRegion() 方法及示例
Java中Java .util.Locale.Builder 类的setRegion(String)方法用于将此Locale.Builder 设置为指定区域。这意味着此方法将设置 Locale.Builder 实例的当前区域以匹配提供的区域并返回它。如果指定区域为 null 或为空,则移除此 LocaleBuilder 的区域。格式正确的区域值由 ISO 3166 标准定义的 2 个字母的区域代码或 3 位的 UN M.49 区域代码组成。
句法:
public Locale.Builder setRegion(String region)
参数:此方法接受区域作为参数,该参数是要设置为此 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 region of Locale.Builder
String region = "IN";
System.out.println("Setting the region: "
+ region);
localeBuilder
= localeBuilder.setRegion(region);
// Displaying Locale.Builder
System.out.println("Updated LocaleBuilder: "
+ localeBuilder);
}
}
输出:
LocaleBuilder: java.util.Locale$Builder@232204a1
Setting the region: IN
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 region of Locale.Builder
String region = "asdasf@!vsd#";
System.out.println("Setting the region: "
+ region);
try {
localeBuilder
= localeBuilder.setRegion(region);
// Displaying Locale.Builder
System.out.println("Updated LocaleBuilder: "
+ localeBuilder);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
LocaleBuilder: java.util.Locale$Builder@232204a1
Setting the region: asdasf@!vsd#
java.util.IllformedLocaleException:
Ill-formed region:
asdasf@!vsd# [at index 0]
参考: https://docs.oracle.com/javase/9/docs/api/ Java/util/Locale.Builder.html#setRegion-java.lang.String-