Menu
CoddyTech

最終課題:Luau台帳

Coddyの「Luau開発者のためのJava」コースのレッスン 47/48。

challenge icon

チャレンジ

簡単

入力は0行以上のname quantity形式の行です。名前は小文字のASCII文字で、数量は符号付き整数です。名前ごとに合計し、合計が0以下のものを除外して、アルファベット順に並べたname:total形式の行を返します。残るものがなければ、emptyを返します。すべての中間合計はintに収まります。

Exercise.solve(List<String> input)から、末尾に改行を付けずに結果のテキストをそのまま返してください。画面に表示されている編集不可のMain.javaは入力行をすべて読み取り、返されたテキストを末尾に改行を1つ付けて出力します。編集可能なメソッド内で出力しないでください。特に指定がない限り、すべての整数と算術演算の結果はJavaのintに収まります。

編集可能なファイル:Exercise.java、Text.java。Text.javaには、再利用可能な解析・整形用ヘルパーが用意されています。すべてのファイルは名前なしパッケージに属し、まとめてコンパイルされます。Main.javaが唯一のエントリーポイントであり、編集できません。

この完全なLuauの参照プログラムを、Javaの複数ファイルAPIに移植してください。このプログラムは同じ有効な行の仕様を実装しており、すべての中間合計はJavaのintに収まります。

local totals: {[string]:number}={}
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: {string}={}
for name,total in pairs(totals) do
    if total>0 then table.insert(names,name) end
end
table.sort(names)
local result: {string}={}
for _,name in ipairs(names) do
    table.insert(result,name..":"..totals[name])
end
print(if #result>0 then table.concat(result,"\n") else "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));
    }
}

Luau開発者のためのJavaのすべてのレッスン

自分で練習してみよう: Javaオンラインコンパイラ