CodeGym /Java 博客 /随机的 /Java 字符串格式()
John Squirrels
第 41 级
San Francisco

Java 字符串格式()

已在 随机的 群组中发布

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 课程中的视频课程
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION