Menu
CoddyTech

最终挑战:Lua 账本

Coddy 面向 Lua 开发者的 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 是唯一入口点,不能编辑。

将这个完整的 Lua 参考程序移植到 Java 多文件 API。它会读取相同的有效输入行;由于任务范围符合 Java int,Lua 整数运算即可满足要求。

local totals={}
for line in io.lines() do
    local name,quantity=line:match("^%s*([a-z]+)%s+([+-]?%d+)%s*$")
    assert(name and quantity,"invalid row")
    totals[name]=(totals[name] or 0)+tonumber(quantity)
end
local names={}
for name,total in pairs(totals) do
    if total>0 then names[#names+1]=name end
end
table.sort(names)
local result={}
for _,name in ipairs(names) do
    result[#result+1]=name..":"..totals[name]
end
print(#result>0 and table.concat(result,"\n") or "empty")

亲手试试

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));
    }
}

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

自己练习: Java 在线编译器