Menu
CoddyTech

最终:库存台账

Coddy 面向 Kotlin 开发者的 Java 课程的第 47 课,共 48 课。

challenge icon

挑战

简单

输入是零行或多行 name quantity。名称由小写 ASCII 字母组成,数量是带符号的整数。汇总每个名称对应的数量,丢弃总数小于或等于零的项,并按字母顺序返回 name:total 行;如果没有剩余项,则返回 empty。所有中间总数都能用 int 表示。

从 Exercise.solve(List<String> input) 返回不带末尾换行符的精确结果文本。可见且已锁定的 Main.java 会读取所有输入行,并在输出返回文本后添加一个换行符。不要在可编辑的方法中打印内容。除非另有说明,所有整数和算术结果都能用 Java int 表示。

可编辑文件:Exercise.java、Text.java。Text.java 提供可复用的解析和格式化辅助方法。所有文件都位于未命名包中,并会一起编译。Main.java 是唯一入口点,不能编辑。

将这个完整的 Kotlin 参考程序移植到 Java 多文件 API 中。它实现了相同的有效行约定;所有中间总数都能用 Java int 表示。

fun summarize(rows: List<String>): String {
    val totals = sortedMapOf<String, Int>()
    for (row in rows) {
        val (name, text) = row.split(" ")
        totals[name] = (totals[name] ?: 0) + text.toInt()
    }
    val result = totals.entries.filter { it.value > 0 }
        .map { "${it.key}:${it.value}" }
    return if (result.isEmpty()) "empty" else result.joinToString("\n")
}
fun main() {
    val rows = generateSequence { readlnOrNull() }.toList()
    println(summarize(rows))
}

亲手试试

import java.io.*;
import java.util.*;
public class Main {
    private static void check(boolean condition) {
        if (!condition) throw new AssertionError("Required public API behavior failed");
    }
    public static void main(String[] args) throws Exception {
        List<String> input = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = reader.readLine()) != null) input.add(line);
        
        System.out.println(Exercise.solve(input));
    }
}

面向 Kotlin 开发者的 Java中的所有课

自己练习: Java 在线编译器