Menu
CoddyTech

字符串格式化

本课属于 Coddy Java 学习旅程的“基础知识”单元。第 69 课,共 73 课。

在 Java 中,String.format() 是一个强大的方法,可用于创建格式化字符串。它可以让你以清晰且可自定义的方式将文本与变量组合起来。此方法使用格式说明符来定义如何将变量插入字符串。

String.format() 的基本语法是:

String formattedString = String.format("format_string", arg1, arg2, ...);
  • format_string:包含文本和格式说明符的字符串。
  • arg1, arg2, ...:要插入到 format_string 中的变量。

以下是一些常见的格式说明符:

  • %s:插入一个字符串。
  • %d:插入一个十进制整数。
  • %f:插入一个浮点数。
  • %b:插入一个布尔值。
  • %c:插入一个字符。
  • %n:插入一个换行符。

你还可以进一步控制格式:

  • %.2f:将浮点数格式化为保留 2 位小数。
  • %10s:插入字符串,并在 10 个字符宽的字段中右对齐。
  • %-10s:插入一个字符串,并在宽度为 10 个字符的字段中左对齐。
  • %03d:插入一个整数,并在前面补零,使其宽度为 3 位。

下面是一个示例:

String name = "Alice";
int age = 30;
double price = 19.99;

String formatted = String.format("Name: %s, Age: %d, Price: %.2f", name, age, price);
System.out.println(formatted);
// 输出:Name: Alice, Age: 30, Price: 19.99

在这个示例中,%s 会被 name 替换,%d 会被 age 替换,%.2f 会被 price 替换,并格式化为保留两位小数。

challenge icon

挑战

简单

创建一个名为 createFormattedString 的方法,它接受以下参数:

  1. 一个字符串 productName。
  2. 一个整数 quantity。
  3. 一个双精度浮点数 unitPrice。

该方法应返回一个格式化字符串,将这些值按以下格式组合起来:

Product: [productName], Quantity: [quantity], Unit Price: [unitPrice]

将 unitPrice 格式化为小数点后 5 位,将 quantity 格式化为小数点后 1 位(将其转换为 double)。

例如,如果 productName 的值为 "laptop",quantity 的值为 3,unitPrice 的值为 1299.9999,该方法应返回:

Product: laptop, Quantity: 3.0, Unit Price: 1299.99990

亲手试试

import java.util.Scanner;

public class Main {
    public static String createFormattedString(String productName, int quantity, double unitPrice) {
        // 在这里编写代码
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String product = scanner.nextLine();
        int qty = scanner.nextInt();
        double price = scanner.nextDouble();
        String formattedString = createFormattedString(product, qty, price);
        System.out.println(formattedString);
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: Java 在线编译器