📌  相关文章
📜  Java中的 Formatter locale() 方法和示例

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

Java中的 Formatter locale() 方法和示例

locale()方法是Java.util.Formatter的内置方法,它返回一个语言环境。此语言环境由格式化程序构造设置。此对象的具有语言环境参数的格式方法不会更改此值。

语法

public Locale locale()

参数:该函数不接受任何参数。

返回值:如果未应用本地化,则该函数返回 null,否则返回已初始化为格式化程序的语言环境。

异常:如果格式化程序在函数调用之前已关闭,则函数抛出FormatterClosedException

下面是上述函数的实现:

方案一:

// Java program to implement
// the above function
  
import java.util.Formatter;
import java.util.Locale;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Get the string Buffer
        StringBuffer buffer
            = new StringBuffer();
  
        // Object creation
        Formatter frmt
            = new Formatter(buffer,
                            Locale.CANADA);
  
        // Format a new string
        String name = "My name is Gopal Dave";
        frmt.format("What is your name? \n%s !",
                    name);
  
        // Print the Formatted string
        System.out.println(frmt);
  
        // Prints the format that has been set
        // Initially to the formatter
        System.out.println("Locale: "
                           + frmt.locale());
    }
}
输出:
What is your name? 
My name is Gopal Dave !
Locale: en_CA

方案二:

// Java program to implement
// the above function
  
import java.util.Formatter;
import java.util.Locale;
  
public class Main {
  
    public static void main(String[] args)
    {
        try {
  
            // Get the string Buffer
            StringBuffer buffer
                = new StringBuffer();
  
            // Object creation
            Formatter frmt
                = new Formatter(buffer,
                                Locale.CANADA);
  
            // Format a new string
            String name = "My name is Gopal Dave";
            frmt.format("What is your name? \n%s !",
                        name);
  
            // Print the Formatted string
            System.out.println(frmt);
  
            // Formatter closed
            frmt.close();
  
            // Prints the format that has been set
            // Initially to the formatter
            System.out.println("Locale: "
                               + frmt.locale());
        }
        catch (Exception e) {
            System.out.println("Exception is: "
                               + e);
        }
    }
}
输出:
What is your name? 
My name is Gopal Dave !
Exception is: java.util.FormatterClosedException

参考: https: Java/util/Formatter.html#locale()