Java 字符串格式化

JavaJavaBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在 Java 中,String.format() 方法通过结合格式化字符串、区域设置(locale)和参数来格式化字符串。格式化字符串指定了参数应转换成的格式,而区域设置则指定了应使用的任何设置,例如语言或地区。在本实验中,我们将学习如何使用 String.format() 方法来格式化字符串。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java/BasicSyntaxGroup -.-> java/output("Output") java/StringManipulationGroup -.-> java/strings("Strings") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/date("Date") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("Exceptions") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/format("Format") java/SystemandDataProcessingGroup -.-> java/string_methods("String Methods") subgraph Lab Skills java/output -.-> lab-117958{{"Java 字符串格式化"}} java/strings -.-> lab-117958{{"Java 字符串格式化"}} java/date -.-> lab-117958{{"Java 字符串格式化"}} java/exceptions -.-> lab-117958{{"Java 字符串格式化"}} java/format -.-> lab-117958{{"Java 字符串格式化"}} java/string_methods -.-> lab-117958{{"Java 字符串格式化"}} end

创建一个简单的字符串格式化示例

在这一步中,我们将创建一个使用 String.format() 方法格式化字符串的基本示例。

  1. ~/project 目录下创建一个名为 SimpleFormatExample.java 的新 Java 文件。
  2. SimpleFormatExample 类的 main() 方法中,创建一个名为 formattedString 的字符串变量,并将其设置为调用 String.format() 的结果,参数如下:
    1. 字符串 "Hello, %s!" 作为格式化字符串。
    2. 字符串 "world" 作为参数。
  3. 使用 System.out.println() 打印 formattedString 的值。
  4. 保存并关闭 SimpleFormatExample.java 文件。
  5. 在终端中,通过运行以下命令编译 SimpleFormatExample.java 文件:javac SimpleFormatExample.java
  6. 然后,使用命令 java SimpleFormatExample 运行生成的类文件。

以下是代码:

public class SimpleFormatExample {
    public static void main(String[] args) {
        String formattedString = String.format("Hello, %s!", "world");
        System.out.println(formattedString);
    }
}

当你运行代码时,应该会看到以下输出:

Hello, world!

在格式化字符串中使用参数

在这一步中,我们将学习如何在格式化字符串中使用参数来自定义输出。

  1. 在编辑器中打开 SimpleFormatExample.java 文件。
  2. 修改 formattedString 变量,使用参数来指定显示的字符数。将格式化字符串中的 "s" 替换为 ".%d-s",以指定要显示的最大字符数。
  3. 在格式化字符串后添加一个整数参数,表示要显示的最大字符数。
  4. 保存并关闭 SimpleFormatExample.java 文件。
  5. 在终端中,通过运行以下命令编译 SimpleFormatExample.java 文件:javac SimpleFormatExample.java
  6. 然后,使用命令 java SimpleFormatExample 运行生成的类文件。

以下是修改后的代码:

public class SimpleFormatExample {
    public static void main(String[] args) {
        String formattedString = String.format("Hello, %d-s!", 5);
        System.out.println(formattedString);
    }
}

当你运行代码时,应该会看到以下输出:

Hello, 5-s!

使用标志符修改格式化行为

在这一步中,我们将学习如何使用标志符来修改格式化字符串的行为。

  1. 在编辑器中打开 SimpleFormatExample.java 文件。
  2. 修改格式化字符串,通过在 % 符号后添加减号(-)来实现文本的左对齐。
  3. 在格式化字符串中添加一个参数,以指定输出的最小宽度。
  4. 保存并关闭 SimpleFormatExample.java 文件。
  5. 在终端中,通过运行以下命令编译 SimpleFormatExample.java 文件:javac SimpleFormatExample.java
  6. 然后,使用命令 java SimpleFormatExample 运行生成的类文件。

以下是修改后的代码:

public class SimpleFormatExample {
    public static void main(String[] args) {
        String formattedString = String.format("%-10s, world!", "Hello");
        System.out.println(formattedString);
    }
}

当你运行代码时,应该会看到以下输出:

Hello     , world!

使用转换字符格式化不同数据类型

在这一步中,我们将学习如何使用不同的转换字符来格式化不同的数据类型。

  1. 在编辑器中打开 SimpleFormatExample.java 文件。
  2. 修改格式化字符串,使用 %f 转换字符来包含一个浮点数。
  3. 在格式化字符串后添加一个浮点数参数。
  4. 保存并关闭 SimpleFormatExample.java 文件。
  5. 在终端中,通过运行以下命令编译 SimpleFormatExample.java 文件:javac SimpleFormatExample.java
  6. 然后,使用命令 java SimpleFormatExample 运行生成的类文件。

以下是修改后的代码:

public class SimpleFormatExample {
    public static void main(String[] args) {
        String formattedString = String.format("The value of pi is approximately %f", 3.14159265359);
        System.out.println(formattedString);
    }
}

当你运行代码时,应该会看到以下输出:

The value of pi is approximately 3.141593

使用精度修饰符控制显示的数字位数

在这一步中,我们将学习如何使用精度修饰符来控制格式化输出中显示的数字位数。

  1. 在编辑器中打开 SimpleFormatExample.java 文件。
  2. 修改格式化字符串,使用 %f 转换字符来包含一个浮点数。添加精度修饰符(%.2f)以仅显示小数点后两位。
  3. 在格式化字符串后添加一个浮点数参数。
  4. 保存并关闭 SimpleFormatExample.java 文件。
  5. 在终端中,通过运行以下命令编译 SimpleFormatExample.java 文件:javac SimpleFormatExample.java
  6. 然后,使用命令 java SimpleFormatExample 运行生成的类文件。

以下是修改后的代码:

public class SimpleFormatExample {
    public static void main(String[] args) {
        String formattedString = String.format("The value of pi is approximately %.2f", 3.14159265359);
        System.out.println(formattedString);
    }
}

当你运行代码时,应该会看到以下输出:

The value of pi is approximately 3.14

使用 Locales 自定义格式化设置

在这一步中,我们将学习如何使用 locales 自定义格式化设置,例如语言或区域。

  1. 在编辑器中打开 SimpleFormatExample.java 文件。
  2. 修改格式化字符串,使用 %d 转换字符来包含一个数字。
  3. 在格式化字符串后添加一个整数参数。
  4. String.format() 方法中添加第二个参数,以指定要使用的 locale。使用 Locale.FRENCH 常量来指定法语。
  5. 保存并关闭 SimpleFormatExample.java 文件。
  6. 在终端中,通过运行以下命令编译 SimpleFormatExample.java 文件:javac SimpleFormatExample.java
  7. 然后,使用命令 java SimpleFormatExample 运行生成的类文件。

以下是修改后的代码:

import java.util.Locale;

public class SimpleFormatExample {
    public static void main(String[] args) {
        String formattedString = String.format(Locale.FRENCH, "Le nombre est %d", 123456789);
        System.out.println(formattedString);
    }
}

当你运行代码时,应该会看到以下输出:

Le nombre est 123456789

格式化日期和时间值

在这一步中,我们将学习如何使用 String.format() 方法来格式化日期和时间值。

  1. 在编辑器中打开 SimpleFormatExample.java 文件。
  2. 添加 java.util.Calendar 类的导入语句,我们将使用它来创建一个日历实例。
  3. 使用 Calendar.getInstance() 创建一个新的 Calendar 实例。
  4. 修改格式化字符串,使用 %tD 转换字符来包含一个日期。
  5. 在格式化字符串后添加一个 Date 参数,使用 calendar.getTime() 方法获取 Date 值。
  6. 保存并关闭 SimpleFormatExample.java 文件。
  7. 在终端中,通过运行以下命令编译 SimpleFormatExample.java 文件:javac SimpleFormatExample.java
  8. 然后,使用命令 java SimpleFormatExample 运行生成的类文件。

以下是修改后的代码:

import java.util.Calendar;
import java.util.Date;

public class SimpleFormatExample {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        String formattedString = String.format("%tD", calendar.getTime());
        System.out.println(formattedString);
    }
}

当你运行代码时,应该会看到以下输出:

08/22/21

使用大写和小写格式化

在这一步中,我们将学习如何使用 %S%s 转换字符分别将字符串格式化为大写和小写。

  1. 在编辑器中打开 SimpleFormatExample.java 文件。
  2. 修改格式化字符串,使用 %S 转换字符将字符串格式化为大写。
  3. 修改格式化字符串,使用 %s 转换字符将第二个字符串格式化为小写。
  4. 保存并关闭 SimpleFormatExample.java 文件。
  5. 在终端中,通过运行以下命令编译 SimpleFormatExample.java 文件:javac SimpleFormatExample.java
  6. 然后,使用命令 java SimpleFormatExample 运行生成的类文件。

以下是修改后的代码:

public class SimpleFormatExample {
    public static void main(String[] args) {
        String formattedString = String.format("The word %S is in uppercase and %s is in lowercase", "HELLO", "world");
        System.out.println(formattedString);
    }
}

当你运行代码时,应该会看到以下输出:

The word HELLO is in uppercase and world is in lowercase

处理异常

在这一步中,我们将学习使用 String.format() 方法时可能抛出的异常,以及如何处理它们。

  1. 在编辑器中打开 SimpleFormatExample.java 文件。
  2. 修改格式化字符串,使用 %c 转换字符来包含一个字符。
  3. 在格式化字符串后添加一个字符参数。
  4. 保存并关闭 SimpleFormatExample.java 文件。
  5. 在终端中,通过运行以下命令编译 SimpleFormatExample.java 文件:javac SimpleFormatExample.java
  6. 然后,使用命令 java SimpleFormatExample 运行生成的类文件。

以下是修改后的代码:

public class SimpleFormatExample {
    public static void main(String[] args) {
        try {
            String formattedString = String.format("The character is %c", "too long");
            System.out.println(formattedString);
        } catch (Exception e) {
            System.out.println("An exception occurred: " + e.getMessage());
        }
    }
}

当你运行代码时,应该会看到以下输出:

An exception occurred: UString.format: '%c' != java.base/java.lang.String

总结

在本实验中,我们学习了如何在 Java 中使用 String.format() 方法来格式化字符串。我们从一个简单的示例开始,使用格式化字符串和参数生成字符串。然后,我们学习了如何使用不同的转换字符来格式化字符串,以及如何使用精度修饰符和标志来控制输出。我们还学习了如何使用 locales 自定义格式化设置,以及如何格式化日期和时间值。最后,我们讨论了使用 String.format() 方法时可能抛出的一些异常以及如何处理它们。