CodeGym/Java Blog/Toto sisi/Java 字串格式()
John Squirrels
等級 41
San Francisco

Java 字串格式()

在 Toto sisi 群組發布
個成員

Java string.format() 方法是什麼?

Java string format()方法用於透過使用不同的格式說明符來格式化字串、整數、小數值等。此方法使用給定的區域設定、指定的格式化程序和參數傳回格式化的字串。如果未提供區域設置,則它將使用預設區域設定來格式化字串。string.format ()是 Java String類別的靜態方法。 Java 字串格式() - 1語法 有兩種類型的字串format()方法。一個提供了區域設置,另一個沒有提供區域設置,後者使用預設區域設置。
public static String format(Locale loc, String format, Object… args)
public static String format(String format, Object… args)
參數
  1. 將應用於format()方法的區域設定值。
  2. 指定輸出字串的格式。
  3. 格式字串的參數數量範圍為 0 到多個。
返回 它始終根據區域設定返回格式化字串。 異常 format ()方法傳回 2 個異常。
  1. NullPointerException,如果格式為 null,則拋出NullPointerException 。
  2. IllegalFormatException,如果指定的格式非法,或提供的參數不足,則拋出此異常。

格式說明符

讓我們來看一些常用的說明詞。
說明符 描述
%s,%S 字串格式化程式。
%d 十進制整數,僅用於整數。
%o 八進制整數,僅用於整數。
%f,%F 對於十進制數,用於浮點數。
%x,%X 十六進制整數,僅用於整數。
讓我們透過範例來看看這些說明符。

Java String.format() 方法範例

class Main {
    public static void main(String[] args) {
        // Integer value
        System.out.println(String.format("%d", 234));
        // String value
        System.out.println(String.format("%s", "format() method"));
        // Float value
        System.out.println(String.format("%f", 99.99));
        // Hexadecimal value
        System.out.println(String.format("%x", 99));
        // Char value
        System.out.println(String.format("%c", 'f'));
        // Octal value
        System.out.println(String.format("%o", 99));
    }
}
輸出
234 format()方法 99.990000 63 f 143
例子
class Main {
  public static void main(String[] args) {
    int n1 = 99;

    // using two different specifiers for formatting the string
    System.out.println(String.format("%s\nhexadecimal: %x", "Result is", n1));
  }
}
輸出
結果是十六進位:63
例子
// to use Locale
import java.util.Locale;

class Main {
  public static void main(String[] args) {
    int number = 9999999;

    // using the default locale if none specified
    System.out.println(String.format("Number: %,d", number););

    // using the GERMAN locale as the first argument
    System.out.println(String.format(Locale.GERMAN, "Number in German: %,d", number));
  }
}
輸出
編號:9,999,999 德文號碼:9.999.999

結論

我們希望現在您了解什麼是 Java 字串format()方法以及如何針對不同的格式說明符實現它以獲得所需的結果。請隨意練習,並在需要更多幫助時返回。快樂學習! 為了鞏固您所學到的知識,我們建議您觀看我們的 Java 課程中的影片課程
留言
  • 受歡迎
你必須登入才能留言
此頁面尚無留言