Menu
CoddyTech

高级字符串格式化

本课属于 Coddy Java 学习旅程的“逻辑与流程”单元。第 49 课,共 59 课。

Java 中的字符串格式化可以让你使用格式说明符创建格式化字符串。最常用的格式说明符有:字符串使用 %s,整数使用 %d,小数使用 %.2f。

使用多个值格式化字符串:

String name = "John";
int age = 25;
String text = String.format("Name: %s, Age: %d", name, age);

运行上面的代码后,text 的内容是:

Name: John, Age: 25

按指定精度格式化小数:

double price = 19.99;
String formatted = String.format("Price: $%.2f", price);

运行上面的代码后,formatted 中的内容是:

Price: $19.99

challenge icon

挑战

简单

创建一个名为 formatData 的方法,它接收四个参数:

  1. 一个 String(name),表示产品名称
  2. 一个 double(price),表示产品价格
  3. 一个整数(quantity),表示数量
  4. 一个 String(format),表示输出格式类型

该方法应根据以下类型格式化数据:

  • "basic":返回 "ITEM: {name}, PRICE: ${price}"
  • "detailed":返回 "PRODUCT: {name}\nPRICE: ${price}\nQUANTITY: {quantity}"
  • "total":返回 "TOTAL FOR {quantity}x {name}: ${total}"(total = price * quantity)

所有价格都必须恰好保留 2 位小数。

返回消息:

  • 如果任何输入为 null 或格式无效:返回 "Invalid input"

亲手试试

import java.util.Scanner;

public class Main {
    public static String formatData(String name, double price, int quantity, String format) {
        // 在这里编写你的代码
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        double price = Double.parseDouble(scanner.nextLine());
        int quantity = Integer.parseInt(scanner.nextLine());
        String format = scanner.nextLine();
        
        if (name.equals("null")) name = null;
        if (format.equals("null")) format = null;
        
        System.out.println(formatData(name, price, quantity, format));
    }
}
quiz icon自我测试

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

逻辑与流程中的所有课

自己练习: Java 在线编译器